在私有属性上调用empty()

时间:2010-05-12 08:05:43

标签: php oop

我正在使用__get()__set()魔术方法拦截对某些私有属性的外部调用,而无需为每个属性编写setter和getter。到目前为止一切顺利:

<?

class Foo{
    private $id;
    private $info = array();
    private $other;

    public function __set($name, $value){
        switch($name){
            case 'id':
            case 'info':
                return $this->$name = $value;
                break;
            default:
                throw new Exception('Attribute "' . $name . '" cannot be changed from outside the class');
        }
    }

    public function __get($name){
        switch($name){
            case 'id':
            case 'info':
                return $this->$name;
                break;
            default:
                throw new Exception('Attribute "' . $name . '" cannot be read from outside the class');
        }
    }
}

$MyFoo = new Foo;

$MyFoo->id = 33;
$MyFoo->info = array (
  'item_id' => '20',
  'issue' => '53',
);
try{
    $MyFoo->other = 44;
}catch(Exception $e){
    echo 'Exception raised as expected: ' . $e->getMessage();
}

?>

现在我需要测试某个属性(数组)是否仍然为空。我意识到empty($MyFoo->info)总是false所以我查阅了手册,发现__isset()

  

__ isset()通过在不可访问时调用isset()或empty()来触发   属性。

但是,我不清楚如何在代码中实现__isset()。我想它应该返回true或false但是......我可以通过empty()isset()来区分吗?

1 个答案:

答案 0 :(得分:2)

你需要这样做:

public function __isset($name) {
    return isset($this->$name);
}

在这种情况下,isset($MyFoo->info)empty($MyFoo->info)将按预期工作:

// isset($MyFoo->info) --> true
// empty($MyFoo->info) --> false
$MyFoo->info = array(1, 2, 3);

// isset($MyFoo->info) --> true
// empty($MyFoo->info) --> true
$MyFoo->info = array();

// isset($MyFoo->info) --> false
// empty($MyFoo->info) --> true
$MyFoo->info = null;
相关问题