正在确定对象属性是否为空


Determining if object property is empty

我觉得这里缺少了什么。在确定变量是否为空时,我已经使用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);
    }
}

// The Code    
$person = new Person(5);
if (empty($person->number)){
    echo "its empty";
} else {
    echo "its not empty";
}

因此,基本上,$person对象的number属性中应该有一个值(5)。正如您可能已经猜到的,问题是php会回显"它是空的"。但事实并非如此!!!

然而,如果我将属性存储在一个变量中,然后对其求值,它确实有效

那么,确定对象属性是否为空的最佳方法是什么呢?非常感谢。

您需要实现__isset()魔术方法。

__通过对不可访问的属性调用isset()或empty()来触发isset(()。

public function __isset($property){
    return isset($this->$property);
} 
if (empty(($person->number)))
/* OR */
if (!isset($person->nothing) || empty(($person->nothing)))

在Object->Property值周围放置()将强制在调用空值之前对其进行求值。

检查返回值是否为null。应该给你正确的答案。