phpdynamic-properties

How do you access a dynamic property in an object?


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.


Solution

  • 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.