简体   繁体   中英

php, dynamically creating variables

(Sorry for my bad English, I use Google Translate)

I'm facing the problem of dynamically creating variables in the class. There are classes at the entrance to __construct transferred to variables.
Further cycles

foreach ($collector as $key => $field) {
    $this->$key = $field; 
} 

Variables are added to the class.
But this code works in other classes, except one. Here is the class

foreach ($collector as $key => $field) {
     $this->$key = $field;
            if (isset($this->$key))
              var_dump($this->$key);
        }
     var_dump('<pre>',$collector);
     var_dump($this);
     die();

var_dump('<pre>',$collector) - dumps the object

if (isset($this->$key))
var_dump($this->$key)

call magic __get(); since there is no variable

var_dump($this) - dumps the object but necessary variables I can not see.

Help me, please!

You could do something like this:

class MyClass
{
    private $_dynamic;

    function __get($name)
    {
        return $this->_dynamic[$name];
    }

    function __set($name, $value)
    {
        $this->_dynamic[$name] = $value;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM