Search code examples
phpvariablesvariable-variablesobject-properties

Using a variable variable in an object property in PHP


I've set a few variables:

$field = "XYZ";
$block_hi = $field."_hi";
$block_lo = $field."_lo";

Then I have an object with properties that have the name of my above variables:

$obj->XYZ_hi['val'] = "value1";
$obj->XYZ_lo['val'] = "value2";

I thought I could use PHP's variable variables to reference the properties:

print( $obj->${$block_hi}['val'] );
print( $obj->${$block_lo}['val'] );

I expected to get:

value1
value2

However those lines throw errors in apache's error_log:

PHP Fatal error:  Cannot access empty property in script.php

Solution

  • This would work, you had the double $$ which wasn't needed in this instance.

     $field = "XYZ";
     $block_hi = $field."_hi";
     $block_lo = $field."_lo";
    
     print($node->{$block_hi}['val']);
     print($node->{$block_lo}['val']);