在对象外部使用isset()方法有两种情况:
如果参数是公有属性,那么可以利用isset()方法判断属性是否被设置;
如果参数是私有属性,isset()方法将无法使用。
那么,是否有办法判断私有属性被设置呢?当然,只需要在类里定义__isset()方法,就可以在对象外部利用isset()方法判断某个私有属性是否被设置了。
对未定义或没有权限访问的属性调用isset()或empty()时,就会调用__isset()方法。
示例代码如下:
class Person
{
public $sex;
private $name;
private $age;
public function __construct($name="", $age=25, $sex='Male')
{
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
/**
* @param $content
*
* @return bool
*/
public function __isset($content) {
echo "The {$content} property is private,the __isset() method is called automatically.
";
echo isset($this->$content);
}
}
$person = new Person("John", 25); // 赋初始值
echo isset($person->sex),"
";
echo isset($person->name),"
";
echo isset($person->age),"
";
输出结果如下:
1
The name property is private,the __isset() method is called automatically.
1
The age property is private,the __isset() method is called automatically.
1