0

I have a class that overrides __get before returning a value. How come it always returns true for empty()? It acts like if __call returns a value after the function empty rather than before.

<?php
  class ref_dummy {
    private $_data = array();
    public function __get($name) {
      if (array_key_exists($name, $this->_data)) return $this->_data[$name];
      $this->_data[$name] = 'bar'; // load sample data
      return $this->_data[$name];
    }  
  }

  $dummy = new ref_dummy();

  if (empty($dummy->foo)) echo 'is empty' . '<br/>';
  else echo $dummy->foo . '<br/>';
?>

I know if($dummy->foo) works but I'm wondering why empty() doesn't.

Fiddle: http://phpfiddle.org/main/code/dak-fjx

4

2 回答 2

1

要通过空检查,您需要实现魔术__isset。在你的情况下,它会很简单

public function __isset($name){
    return isset($this->_data[$name]);
}
于 2013-06-06T05:29:13.687 回答
1

该线程解决了我的问题:empty() 在对象的非空属性上返回 TRUE

解决方案是同时使用 __get 和 __isset。

  class ref_dummy {

    private $_data = array();

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

    public function __get($name) {
      if (array_key_exists($name, $this->_data)) return $this->_data[$name];
      $this->_data[$name] = 'bar'; // load sample data
      return $this->_data[$name];
    }
  }
于 2013-06-06T05:27:37.167 回答