我正在尝试使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";
如果符合以下情况,我该怎么做空/ isset返回true / false:
my_stuff
未设置,或者empty()
答案 0 :(得分:8)
public function __isset($name){
$getter = 'get'.ucfirst($name);
return method_exists($this, $getter) && !is_null($this->$getter());
}
检查$getter()
是否存在(如果它不存在,假定该属性也不存在)并返回非空值。所以NULL
将导致它返回false,正如您在阅读isset()
的php手册后所期望的那样。
答案 1 :(得分:3)
更多选择不依赖于getter
public function __isset($name)
{
$getter = 'get' . ucfirst($name);
if (method_exists($this, $getter)) {
return !is_null($this->$getter());
} else {
return isset($this->$name);
}
}
答案 2 :(得分:1)
由于以下行,您的代码会返回错误:
if(method_exists($this, $getter))
return isset($this->$getter());
您只需将其替换为:
if (!method_exists($this), $getter) {
return false; // method does not exist, assume no property
}
$getter_result = $this->$getter();
return isset($getter_result);
如果未定义getter或返回NULL
,则返回false。我建议你最好考虑一下你确定某些属性的方式。
上面的代码也假设您正在为所有属性创建getter,因此当没有getter时,该属性被假定为未设置。
另外,你为什么要使用吸气剂?他们似乎有点矫枉过正。