Quantcast
Channel: 民工的博客 » PHP应用
Viewing all articles
Browse latest Browse all 7

对重载的属性使用 empty() 时,重载魔术方法将不会被调用

$
0
0

之前一直没注意魔术方法详细情况,今天看到这样一个Notice:

在除 isset() 外的其它语言结构中无法使用重载的属性,这意味着当对一个重载的属性使用 empty() 时,重载魔术方法将不会被调用。

为避开此限制,必须将重载属性赋值到本地变量再使用 empty()

测试代码:

class test {

    public function __get($name){
        echo "__get被调用";
        return isset($this->$name) ? $this->$name : false;
    }

    public function __set($name,$value){
        echo "__set被调用";
        $this->$name = $value;
        return false;
    }

    public function __isset($name){
        echo "__isset被调用";
        return isset($this->$name) ? $this->$name : false;
    }
}
$t = new test();
$c = $t->a;     //此时赋值 c 为 false
var_dump($c);   // false
$t->a = 123;    //调用 __set创建变量并赋值
echo empty($t->a)? ' 1 ' : ' 2 ';   //此时通过 __get ->  __isset 获取返回值 true (上面) 输出2

echo empty($c) ? ' 1 ' : ' 2 ';     // 1
/**输出结果:
__get被调用
__isset被调用
boolean false
__set被调用
2 1
*/

结论:不管在类内部,还是外部对重载属性进行 empty/isset时,都会调用 __isset


Viewing all articles
Browse latest Browse all 7

Latest Images

Trending Articles





Latest Images