can i use stdClass like an array?

后端 未结 6 901
爱一瞬间的悲伤
爱一瞬间的悲伤 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:33

    An object is not an array. If you want numerically indexed elements, use an array.

    If you want named elements use either an Object or an Associative Array.

    As for why you're getting different behaviour, it's because in the Array, you are not specifying an index, so PHP uses the length of the Array as the index. With the Object, you have to specify the name (in this case 'a').

    The other thing you may want to do is have an Object, with a member that is an array:

    $obj = new stdClass;
    $obj->arr = array();
    $obj->arr[] = 'foo';
    $obj->arr[] = 'bar';
    

    also don't forget you can cast an array to an object:

    $obj = (object) array(
        'arr' => array(
            'foo',
            'bar'
        )
    );
    

提交回复
热议问题