开发者

using the magic __set() method with 2D arrays

If I have the following registry class:

Class registry 
{
    private $_vars;

    public function __construct()
    {
        $this->_vars = array();
    }

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

    public function __get($key)
    {
        if (isset($this->_vars[$key]))
            return $this->_vars[$key];
    }

    public function printAll()
    {
        print "<pre>".print_r($this->_vars,true)."</pre>";
    }
}

$reg = new registry();

$reg->arr = array(1,2,3);
$reg->arr = array_merge($reg->arr,array(4));

$reg->开发者_StackOverflow社区printAll();

Would there be an easier way to push a new item onto the 'arr' array? This code: 'array[] = item' doesn't work with the magic set method, and I couldn't find any useful info with google. Thanks for your time!


If you have:

$reg = new registry();
$reg->arr = array(1,2,3);
$reg->arr = 4;

And you're expecting:

Array
(
    [arr] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )

)

All you need to do is update your __set method to:

public function __set($key, $val){
  if(!array_key_exists($key, $this->_vars)){
    $this->_vars[$key] = array();
  }
  $this->_vars[$key] = array_merge($this->_vars[$key], (array)$val);
}


You need to alter the definition of __get() so that it returns by reference:

public function &__get($key) {
  return $this->_vars[$key];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜