PHP:空不适用于 getter 方法
我有一个“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?';
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?';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
empty()
会先调用__isset()
,只有返回true
才会调用__get()
。实现
__isset()
并使其针对您支持的每个魔法属性返回true
。empty()
will call__isset()
first, and only if it returnstrue
will it call__get()
.Implement
__isset()
and make it returntrue
for every magic property that you support.当使用
empty
进行检查时不会调用Magic getter。该值确实不存在,因此empty
返回true
。您还需要实现 __isset 才能使其正常工作。Magic getters are not called when checking with
empty
. The value really does not exist, soempty
returnstrue
. You will need to implement__isset
as well to make that work correctly.PHP 的神奇的 get 方法是名为
__get()
。$this->stuff
不会调用getStuff()
。试试这个:PHP's magic get method is named
__get()
.$this->stuff
will not callgetStuff()
. Try this: