我试图让像 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 返回真/假:
my_stuff
上面没有设置,或者在 empty()
?
最佳答案
public function __isset($name){
$getter = 'get'.ucfirst($name);
return method_exists($this, $getter) && !is_null($this->$getter());
}
这会检查
$getter()
是否存在(如果不存在,则假定该属性也不存在)并返回一个非空值。所以 NULL
将导致它返回 false,正如您在阅读 isset()
的 php 手册后所期望的那样。关于php - 如何在 PHP 中实现 __isset() 魔术方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6242591/