PHP中的小问题

天台的故事 2014-10-13 09:27:19

<?php
header("Content-type:text/html;charset=utf-8");

class Person{
private $name;
private $age;
private $sex;

public function __construct($name){
$this->name = $name;
$this->age = "23岁";
$this->sex = "男";
}

public function display(){
echo "姓名:$this->name<br>";
echo "年龄:$this->age<br>";
echo "性别:$this->sex<br>";
}

public function __destruct(){
//echo "$this->name: 正在清理内存...<br>";
}

public function __set($propertyName, $propertyValue){
if ($propertyName == "sex"){
if ($propertyValue == "男" || $propertyValue == "女"){
$this->sex = $propertyValue;
}
else{
die("赋值非法,只能是:女|男");
}
}
}

public function __get($propertyName){
if($propertyName == "sex"){
return "保密";
}
else if($propertyName == "age"){
return $this->age;
}
else if($propertyName == "name"){
return $this->name;
}
}

public function __isset($propertyName){
if($propertyName == "name"){
return false;
}
else{
return isset($this->$propertyName);
}
}

public function __unset($propertyName){
if($propertyName == "name"){
return false;
}
else{
unset($this->$propertyName);
}
}

}

$per1 = new Person("Gibi");

$per1->display();

unset($per1->sex);

$per1->display();



?>

为什么我用unset($per1->sex);删除掉类中的sex变量,然后输出是这个变量是保密,而如果删除掉unset($per1->nane);的name变量,输出的是空。请大神解释下。
...全文
201 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
天涯过客009 2014-10-13
  • 打赏
  • 举报
回复
unset($per1->sex)
这样会删除掉$sex变量
因为类中没有这个变量了,如果你再调用,会执行__get.
傲雪星枫 2014-10-13
  • 打赏
  • 举报
回复
为什么我用unset($per1->sex);删除掉类中的sex变量,然后输出是这个变量是保密 unset($per1->sex); 后 $per1中没有sex这个属性了,当调用display时,会触发__get方法。 在__get方法中, if($propertyName == "sex"){ return "保密"; } 所以会输出保密。 如果删除掉unset($per1->name);的name变量,输出的是空。 这个是把 private $name; 这句删除对吗? private $name删除后,会执行__construct() 中的 $this->name = $name; 因为Person没有$name这个属性,所以会调用__set方法,而__set方法中,只有propertyName==sex的处理方法,所以执行完__set后,Person还是没有$name属性。 display时,因为没有$this->name,所以会调用__get方法。而__get方法对name的处理是返回$this->name。所以为空了。 如果想$name不为空,可以在__set方法中加入 if ($propertyName == 'name'){ $this->name = '111'; } 这样就可以输出 姓名:111 年龄:23岁 性别:男

21,881

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧