如何在PHP中实现__isset()魔术方法?

Ale*_*lex 11 php class isset magic-methods

我正在尝试使用类似函数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);   
  }

}
Run Code Online (Sandbox Code Playgroud)

用法:

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";
Run Code Online (Sandbox Code Playgroud)

http://codepad.org/QuPNLYXP

如果符合以下情况,我该如何将其设为空/ isset返回true/false:

  • my_stuff 上面没有设置,或者有空值或零值 empty()
  • 该方法不存在(不确定是否需要,因为我认为你得到了一个致命的错误)

Arj*_*jan 8

public function __isset($name){
    $getter = 'get'.ucfirst($name);
    return method_exists($this, $getter) && !is_null($this->$getter());
}
Run Code Online (Sandbox Code Playgroud)

检查是否$getter()存在(如果它不存在,则假定该属性也不存在)并返回非空值.所以NULL会导致它返回false,正如您在阅读php手册后所期望的那样isset().

  • 它更快,但差异非常小.无论你使用`!== null`还是`!is_null()`都是品味,而不是速度优化. (3认同)