我觉得我在这里错过了一些东西.我现在一直在使用PHP的empty()函数确定变量是否为空.我想用它来确定对象的属性是否为空,但不知何故它不起作用.这是一个简化的类来说明问题
// The Class
class Person{
private $number;
public function __construct($num){
$this->number = $num;
}
// this the returns value, even though its a private member
public function __get($property){
return intval($this->$property);
}
}
Run Code Online (Sandbox Code Playgroud)
// The Code
$person = new Person(5);
if (empty($person->number)){
echo "its empty";
} else {
echo "its not empty";
}
Run Code Online (Sandbox Code Playgroud)
所以基本上,$person对象的number属性应该有一个值(5).你可能已经猜到了,问题是php回应"它是空的".但它不是!!!
但是,如果我将属性存储在变量中,然后对其进行评估,它确实有效.
那么确定对象属性是否为空的最佳方法是什么?谢谢.
xda*_*azz 24
你需要实现__isset()魔术方法.
通过在不可访问的属性上调用isset()或empty()来触发__isset().
public function __isset($property){
return isset($this->$property);
}
Run Code Online (Sandbox Code Playgroud)