1

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?

John Aston
  • 127
  • 3

2 Answers2

0

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;
Radko Dinev
  • 865
  • 7
  • 15
0

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
Edmhs
  • 3,645
  • 27
  • 39