i have array look like this:
$config = array(
'id' => 123,
'name' => 'bla bla',
'profile' => array(
'job' => 'coder',
'more' => 'info'
)
);
i want to create class Config look like this:
$c = new Config($config);
echo $c->profile->more;
somebody can help me?
You can do this in the constructor of your Config class:
$object = json_decode(json_encode($array), false);
In general, if your array is flat (no nesting), then you could also use:
$object = (object)$array;
On class construct create config objects from array. If you want more then look at __set() __get() __call() class functions.
Working code:
$config = array(
'id' => 123,
'name' => 'bla bla',
'profile' => array(
'job' => 'coder',
'more' => 'info'
)
);
class Config{
public function __construct($data){
foreach($data as $k => $v){
$this->{$k} = (object)$v;
}
}
}
$c = new Config($config);
print_r($c);
echo $c->profile->job;
Response:
Config Object
(
[id] => stdClass Object
(
[scalar] => 123
)
[name] => stdClass Object
(
[scalar] => bla bla
)
[profile] => stdClass Object
(
[job] => coder
[more] => info
)
)
coder