重载的__get是否需要管理所有成员变量?

时间:2009-05-22 04:15:49

标签: php variables methods overloading member

我正在为类创建一个__get()函数来控制对私有成员变量的访问。我是否需要设计函数来处理所有可能的成员值读取,或者我是否可以不为公共成员编写它?另外,我假设继承此类的类将使用我的__get()函数来访问私有成员。

class ClassA{
  private $collection = array();
  public $value;

  function __get($item){
    return $collection[$item];
  }

3 个答案:

答案 0 :(得分:1)

不,你没有。


class A {
   public $foo = 'bar';
   private $private = array();

   public function __get($key) {
      echo 'Called __get() at line #' ,__LINE__, ' with key {', $key ,'}',"\n";
      return $this->private[$key];
   }

   public function __set($key, $val) {
      $this->private[$key] = $val;
   }
}


$a = new A();

var_dump($a->foo);
$a->bar = 'baz';
var_dump($a->bar);

是的,它会:


class B extends A { private $private = array(); }
$b = new B();
var_dump($b->bar);

答案 1 :(得分:0)

好吧,你的代码会在你的数组中没有设置的私有项上失败。但话说回来,你可以用这个来处理数组内外的内容;

  function __get($item){
    if ( isset ( $collection[$item] ) )
       return $collection[$item];
    else {
       try {
          return $this->$item ;  // Dynamically try public values
       } catch (Exception $e) {
          $collection[$item] = 0 ; // Make it exist
       }
    }
  }

继承调用的类将使用此__get(),但可以重写,因此请使用parent :: __ construct()表示明确。还要注意,这些不能是静态的。 Further reading

答案 2 :(得分:0)

首先,PHP在类定义中搜索属性名称并尝试返回其值。如果没有属性 - PHP尝试调用__get($ var),在这里你可以返回任何你想要的东西。对于那些知道类似Java的getter / setter的人来说,这是一个有点混乱的行为,你必须为你想要访问的每个类成员定义它们。

当使用类似Java的getter / setter时感觉很舒服 - 你可能会这样写:

public function __set($var, $value)
{
    if (method_exists($this, $method = "_set_" . $var))
    {
        call_user_func(array($this, $method), $value);
    }
}
public function __get($var)
{
    if (method_exists($this, $method = "_get_" . $var))
    {
        return call_user_func(array($this, $method), $value);
    }
}

然后通过定义自定义getter / setter

来使用此代码
protected function _get_myValue() 
     {
         return $this->_myValue; 
     }
protected function _set_myValue($value)
{
    $this->_myValue = $value;
}

以这种方式访问​​已定义的方法:

$obj->myValue = 'Hello world!';