views:

170

answers:

1

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->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!

+2  A: 

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);
}
macek
hiya, that's a pretty good solution to the problem, thanks very much!
Spoonface
@Spoonface, no problem :)
macek