在php中将数组转换为对象类

时间:2022-12-20 20:22:00

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:

我想创建类Config看起来像这样:

$c = new Config($config);

echo $c->profile->more;

somebody can help me?

有人可以帮帮我吗?

2 个解决方案

#1


0  

You can do this in the constructor of your Config class:

您可以在Config类的构造函数中执行此操作:

$object = json_decode(json_encode($array), false);

In general, if your array is flat (no nesting), then you could also use:

一般来说,如果你的数组是扁平的(没有嵌套),那么你也可以使用:

$object = (object)$array;

#2


0  

On class construct create config objects from array. If you want more then look at __set() __get() __call() class functions.

在类构造中从数组创建配置对象。如果你想要更多,那么看看__set()__ get()__ call()类函数。

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

#1


0  

You can do this in the constructor of your Config class:

您可以在Config类的构造函数中执行此操作:

$object = json_decode(json_encode($array), false);

In general, if your array is flat (no nesting), then you could also use:

一般来说,如果你的数组是扁平的(没有嵌套),那么你也可以使用:

$object = (object)$array;

#2


0  

On class construct create config objects from array. If you want more then look at __set() __get() __call() class functions.

在类构造中从数组创建配置对象。如果你想要更多,那么看看__set()__ get()__ call()类函数。

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