php - __isset 未返回正确的结果

标签 php magic-methods

我正在尝试使用神奇的 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 应返回 TRUEFALSE。如果变量存在并且具有值,则为 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/

相关文章:

php - 使用 RIGHT JOIN 将页面数据匹配到页面

python - python del 语句的神奇方法?

python - 创建通常看起来像 float 的类对象

python - 返回类型不同,重载__add__

php - 如何使用 watir-webdriver 遍历 DOM(子级/兄弟级)?

php - MySQL/PHP : Update MySQL with Ajax

php - 显示 2 个日期之间的行数

php - Magento 中的购物车总计不含运费

python - 与 NumPy 实例调用的相等性比较 `__bool__`

Python 字典 "plus-equal"行为