本文介绍了PHP:empty不使用getter方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个getter方法,如

I have a "getter" method like

function getStuff($stuff){
  return 'something';
}

> stuff),我总是得到 FALSE ,但我知道 $ this-> stuff

if I check it with empty($this->stuff), I always get FALSE, but I know $this->stuff returns data, because it works with echo.

如果我用!isset($ this-> stuff) code>我得到正确的值,条件从不执行...

and if I check it with !isset($this->stuff) I get the correct value and the condition is never executed...

这里是测试代码:

class FooBase{

  public function __get($name){
    $getter = 'get'.ucfirst($name);
    if(method_exists($this, $getter)) return $this->$getter();
    throw new Exception("Property {$getter} is not defined.");
  }
}

class Foo extends FooBase{
  private $my_stuff;

  public function getStuff(){
    if(!$this->my_stuff) $this->my_stuff = 'whatever';
    return $this->my_stuff;
  }

}

$foo = new Foo();
echo $foo->stuff;

if(empty($foo->stuff)) echo 'but its not empty:(';
if($foo->stuff) echo 'see?';


推荐答案

empty c $ c>将首先调用 __ isset(),只有当它返回 true 才会调用 __get()

empty() will call __isset() first, and only if it returns true will it call __get().

实现 __ isset() code> true

Implement __isset() and make it return true for every magic property that you support.

function __isset($name)
{
    $getter = 'get' . ucfirst($name);
    return method_exists($this, $getter);
}

这篇关于PHP:empty不使用getter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 15:41