Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?';
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
847 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...