PHP Objects with Int Variables

I noticed something rather strange with PHP objects and cannot find the documented reason.

The following code shows the behavior

<?php $a = (object) array( 0 => 1 ); foreach($a as $b => $c) { $a->$b = ++$c; //I'm expecting the key to be overwritten here } var_dump($a); $var = 0; var_dump($a->$var); $var = "0"; var_dump($a->$var); 

and exit

 object(stdClass)#1 (2) { [0]=> int(1) ["0"]=> int(2) } int(2) int(2) 

Is the numerical part of the class inaccessible using the syntax -> ?

+6
source share
2 answers

When you cast (object) in an array, you advertise this array as a list of the internal properties of an anonymous object (i.e. stdClass).

How properties are indexed in an object is slightly different from array properties; in particular, property names of objects are always treated as strings, while array indices are scanned based on the expected type (for example, numeric strings are treated as integers).

The above behavior does not affect foreach loops because there is no hashing; as for PHP, a regular array is repeated.

To answer your question, yes, using the -> operator it -> not possible to get numeric keys from the original array. To avoid this, you must remove the numerical indices from your array before doing the translation.

It's hard to find this behavior in the documentation, but a hint of it can be found here :

If the object is converted to an array, the result is an array whose elements are the properties of the object. Keys are member variable names with a few notable exceptions: integer properties are not available ...

Fyi

In this particular case, you can work around the problem using links; this is not recommended, please follow the directions below without using numeric property names:

 foreach ($a as &$c) { ++$c; } unset($c); 

Update

2014-11-26: I updated the documentation; live pages will be updated this Friday - commit .

+5
source

stdClass processes data terribly freely, since it is an object representation of an internal array (thus, the ability to cast without problems).

 $stdClassObject->property = "value"; 

The property is treated as a string, but during casting the type of the property does not change (something is clear, as if you would throw the object and then into the array again, you would lose the whole integer indices).

I don't think they could do better, but you can create your own alternative to stdClass :-)

+1
source

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


All Articles