PHP: empty doesn't work with a getter method

前端 未结 3 617
北恋
北恋 2020-12-18 22:12

I have a \"getter\" method like

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

if I check it with empty($this->stuff)

相关标签:
3条回答
  • 2020-12-18 22:27

    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);
    }
    
    0 讨论(0)
  • 2020-12-18 22:28

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-18 22:38

    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

    0 讨论(0)
提交回复
热议问题