PHP: empty doesn't work with a getter method

荒凉一梦 提交于 2019-12-22 03:36:08

问题


I have a "getter" method like

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

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

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

here's the test code:

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?';

回答1:


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

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);
}



回答2:


Magic getters are not called when checking with empty. The value really does not exist, so empty returns true. You will need to implement __isset as well to make that work correctly.

__isset() is triggered by calling isset() or empty() on inaccessible properties.

http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members




回答3:


PHP's magic get method is named __get(). $this->stuff will not call getStuff(). Try this:

public function __get($property) {
    if ($property == 'stuff') {
        return $this->getStuff();
    }
}


来源:https://stackoverflow.com/questions/6241039/php-empty-doesnt-work-with-a-getter-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!