如何在PHP中实现__isset()魔术方法?
发布时间:2020-12-13 17:28:37 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试使用像empty()和isset()这样的函数使用方法返回的数据. 我到目前为止 abstract class FooBase{ public function __isset($name){ $getter = 'get'.ucfirst($name); if(method_exists($this,$getter)) return isset($this-$getter()); // not worki
我正在尝试使用像empty()和isset()这样的函数使用方法返回的数据.
我到目前为止 abstract class FooBase{ public function __isset($name){ $getter = 'get'.ucfirst($name); if(method_exists($this,$getter)) return isset($this->$getter()); // not working :( // Fatal error: Can't use method return value in write context } public function __get($name){ $getter = 'get'.ucfirst($name); if(method_exists($this,$getter)) return $this->$getter(); } public function __set($name,$value){ $setter = 'set'.ucfirst($name); if(method_exists($this,$setter)) return $this->$setter($value); } public function __call($name,$arguments){ $caller = 'call'.ucfirst($name); if(method_exists($this,$caller)) return $this->$caller($arguments); } } 用法: class Foo extends FooBase{ private $my_stuff; public function getStuff(){ return $this->my_stuff; } public function setStuff($stuff){ $this->my_stuff = $stuff; } } $foo = new Foo(); if(empty($foo->stuff)) echo "empty() works! n"; else "empty() doesn't work:( n"; $foo->stuff = 'something'; if(empty($foo->stuff)) echo "empty() doesn't work:( n"; else "empty() works! n"; http://codepad.org/QuPNLYXP 如何使它如此空/ isset返回true / false如果: > my_stuff以上没有设置,或者在空()的情况下有一个空值或零值 ? public function __isset($name){ $getter = 'get'.ucfirst($name); return method_exists($this,$getter) && !is_null($this->$getter()); } 这检查$getter()是否存在(如果不存在,则假定该属性也不存在)并返回非空值.因此,NULL将导致它返回false,正如您在阅读 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |