Using the magic __set () method with two-dimensional 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->printAll();

Would there be an easier way to insert a new element into an arr array? This code: "array [] = item" does not work with the magic set method, and I could not find useful information on Google. Thank you for your time!

+3
source share
2 answers

If you have:

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

And you expect:

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

)

All you have to do is update your method __setto:

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);
}
+4
source

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

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

Source: https://habr.com/ru/post/1740971/


All Articles