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

前端之家收集整理的这篇文章主要介绍了如何在PHP中实现__isset()魔术方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用像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以上没有设置,或者在空()的情况下有一个空值或零值
>该方法不存在(不知道如果neeed,因为我认为你得到一个致命的错误)

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

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

原文链接:https://www.f2er.com/php/131657.html

猜你在找的PHP相关文章