PHP listing array for an object

Possible duplicate:
Traversing an array with numeric keys as an object

I did a casting from array to object, and I'm confused:

$arr = range(1,3); $obj = (object) $arr; var_dump($obj) object(stdClass)#2 (5) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } 

The question arises: how to access the attributes of an object in this case? $obj->0 causes a syntax error.

+6
source share
3 answers

You cannot access these properties of the object unless you return to the array. Period. If you need to do this for some reason, set the array keys to something else.

+4
source

In this case, the only thing I can think of is to access the properties using foreach as follows:

 foreach($obj as $key => $value) var_dump("$key => $value"); 

but of course, this will not solve the main problem.

+2
source

It looks like the ArrayObject class can access properties

 $a = new ArrayObject($obj); echo $a[0]; 
+1
source

Source: https://habr.com/ru/post/913656/


All Articles