PHP:empty不';不要使用getter方法

PHP:empty不';不要使用getter方法,php,class,getter,Php,Class,Getter,我有一个“getter”方法,比如 function getStuff($stuff){ return 'something'; } 如果我用empty($this->stuff)检查它,我总是得到FALSE,但我知道$this->stuff返回数据,因为它与echo一起工作 如果我用检查它!isset($this->stuff)我得到了正确的值,并且该条件从未执行过 以下是测试代码: class FooBase{ public function __get($name){

我有一个“getter”方法,比如

function getStuff($stuff){
  return 'something';
}
如果我用
empty($this->stuff)
检查它,我总是得到
FALSE
,但我知道
$this->stuff
返回数据,因为它与echo一起工作

如果我用
检查它!isset($this->stuff)
我得到了正确的值,并且该条件从未执行过

以下是测试代码:

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?';
PHP的名称为
\uu get()
$this->stuff
不会调用
getStuff()
。试试这个:

public function __get($property) {
    if ($property == 'stuff') {
        return $this->getStuff();
    }
}
使用
进行检查时,不会调用Magic Getter。该值实际上不存在,因此
empty
返回
true
。您还需要实现
\uu isset
,以使其正常工作

\uu isset()
通过调用不可访问属性上的
isset()
empty()
来触发

empty()
将首先调用
\uu isset()
,只有当它返回
true
时,才会调用
\uu get()

实现
\uu isset()
,并为您支持的每个magic属性返回
true

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

但我有。我用两个调用我的方法的uuu get和uu set函数创建了一个类,并对其进行了扩展。。它适用于
isset()
,但不适用于
empty()
:(是的,发布您正在使用的实际代码通常比某些示例代码更可取,因为这些示例代码实际上并不做您正在做的事情。:)我的问题是,在这种情况下empty()为什么不报告正确的值?像这样<代码>公共函数uu isset($name){$getter='get'.ucfirst($name);如果(方法_存在($this,$getter))返回true;}从您的示例判断,是的,这似乎是正确的方法。我用一个简短的代码更新了我的答案。我认为这是一个正确的答案。函数上的
empty
也会给我们带来错误,因此当前的php行为在形式上有一个bug,因为它允许调用函数上的empty(即使它们很神奇)。隐马尔可夫模型。。。但它们是魔法。所以,让它不是bug,而是特性。