可以为数组和非数组类成员变量使用魔术方法__get和__set吗?

时间:2014-06-13 10:50:53

标签: php arrays oop getter-setter magic-methods

我目前在PHP类示例中有以下__get / __ set方法:

class example{

    /*Member variables*/
    protected $a; 
    protected $b = array(); 

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

    public function __set($name, $value){
        $this->$name = $value;
    }

}

但是,除了设置标准的受保护变量之外,我还希望能够在类中设置受保护的数组。我已经查看了一些其他问题,并找到了关于如何使用__get / __ set方法简单设置变量的一般建议,但没有任何允许使用这些魔术方法来设置BOTH数组和非数组的方法,即以下列方式:

$fun = new $example(); 
$fun->a = 'yay'; 
$fun->b['coolio'] = 'yay2'; 

1 个答案:

答案 0 :(得分:5)

简单,像这样定义__get()

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

// ...

$fun = new example();
$fun->a = 'yay';
$fun->b['coolio'] = 'yay2';
var_dump($fun);

输出:

object(example)#1 (2) {
  ["a":protected]=>
  string(3) "yay"
  ["b":protected]=>
  array(1) {
    ["coolio"]=>
    string(4) "yay2"
  }
}

当您处理参考文献时,请务必小心谨慎,并且很容易陷入困境并引入难以追踪的错误。