加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

如何在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以上没有设置,或者在空()的情况下有一个空值或零值
>该方法不存在(不知道如果neeed,因为我认为你得到一个致命的错误)

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读