1

I am casting an array as an object and attempting to access the key (or property), but it is not working. The below code returns type 8 -- Undefined property: stdClass::$2. I attempted to use property_exists(), but that also failed.

$var = (object)array('1' => 'Object one','2' => 'Object two');
$num = "2";
var_dump( $var->$num );

Does anyone know why?

UPDATE: This seems to be an issue regardless if the properties are strings or integers.

Bobby Bruce
  • 341
  • 5
  • 12
  • Possible duplicate of [How can I access an object property named as a variable in php?](https://stackoverflow.com/questions/3515861/how-can-i-access-an-object-property-named-as-a-variable-in-php) – Pranav C Balan Apr 10 '19 at 19:56
  • the problem is the numeric key/propertyname. If you name it "a2" it'll work with your code: https://3v4l.org/JiU9A – Jeff Apr 10 '19 at 19:57
  • @PranavCBalan I doubt this is a dupe, because the answers in the poss dupe will not work - (except in php >7.2): `$var->{$num}` – Jeff Apr 10 '19 at 20:05
  • @Jeff : yes you are right... – Pranav C Balan Apr 10 '19 at 20:08
  • Possible duplicate of [How to access object properties with names like integers?](https://stackoverflow.com/questions/10333016/how-to-access-object-properties-with-names-like-integers) – miken32 Apr 10 '19 at 21:19

1 Answers1

1

This won't work in PHP < 7.2.0 and the issue is that the string-integer array keys are actually converted to integer property names, not strings. An alternate way to get an object from an array that will work:

$var = json_decode(json_encode(array('1' => 'Object one','2' => 'Object two')));
$num = "2";
var_dump( $var->$num );

See the Demo, in PHP < 7.2.0 the (object) cast converts to integer properties but json_decode creates string properties.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87