我正在尝试使用神奇的 php 函数将对象链接在一起。
我有一个名为 page 的抽象类,我网站中的每个页面都扩展了该类。 在这个抽象类构造函数中,我尝试获取像这样的用户对象:
public function __construct( ){
$user = new user();
$this->user = $user->getIdentity();
$this->getHeader();
$this->switchAction( );
$this->getFooter();
}
现在在我的页面中我可以使用 $this->user 并且它工作得很好。如果用户登录,则返回用户对象。 在我的用户类中,我有一个神奇的 __get 和 __isset 函数:
public function __get ( $name ){
switch ($name){
case 'oAlbums':
return $this->oAlbums = album::get_ar_obj($arWhere = array('user_id' => $this->id) );
break;
public function __isset ( $name ){
switch($name){
case 'oAlbums':
echo 'magic isset called, trying to call '. $name . '<br />';
return isset($this->$name);
break;
}
}
因此,在页面中时,我想通过调用 $this->user->oAlbums
来检查用户是否有任何相册。
正如预期的那样,这将返回一个包含所有专辑对象的数组。但是当我这样做时
if(empty( $this->user->oAlbums ))
echo 'still give smepty';
在我的页面中,它仍然回显字符串..
为什么 __isset 函数不起作用?
最佳答案
__isset
应返回 TRUE
或 FALSE
。如果变量存在并且具有值,则为 TRUE,否则为 FALSE。您实际上正在返回 $this->name
的值。您应该只返回 is_null($this->name)
。将代码更改为:
public function __get ( $name ){
switch ($name){
case 'oAlbums':
return $this->oAlbums = album::get_ar_obj($arWhere = array('user_id' => $this->id) );
break;
}
}
public function __isset ( $name ){
switch($name){
case 'oAlbums':
echo 'magic isset called, trying to call '. $name . '<br />';
return !is_null($this->$name);
break;
default:
return FALSE;
}
}
关于php - __isset 未返回正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16326066/