can i use stdClass like an array?

后端 未结 6 892
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 08:21

is it possible to make stdClass objects work like a generically indexed array?

i.e. $array = Array ( [0] => 120 [1] => 382 [2] => 552 [3] => 595 [4] => 616 )

wou

6条回答
  •  孤街浪徒
    2021-01-23 08:52

    No, you can't. Using the brackets ([]) like that is called "ArrayAccess" in PHP, and is not implemented on the stdClass object.

    It sounds like you might want something like

    $foo = new stdClass();
    $foo->items = array();
    $foo->items[] = 'abc';
    $foo->items[] = '123';
    $foo->items[] = 'you and me';
    

    You could also try casting an array as a stdClass to see what happens.

    $foo = array();
    $foo[] = 'abc';
    $foo[] = '123';
    $foo[] = 'you and me';
    $foo = (object) $foo;
    var_dump($foo);
    

提交回复
热议问题