Calling properties dynamically in PHP

November 6, 2007

development php

I often forget how useful curly brackets can be. For example from within a double quoted string you can do more than basic variable replacement.

$obj->property = 'property from an object';
print $foo = "This string includes a {$obj->property}.";

But a use that is not seen as commonly is the ability to call a property of an object dynamically. I sometimes see this with a single variable:

$prop_str = 'property';
print $obj->$prop_str;

However, this has it’s limits when writing object oriented programmes when the string you want to use as the property name is within another object. You would have to pull it out into a temporary variable:

$tmp_str = $foo->bar->baz;
print $obj->$tmp_str;

With curly brackets you can cut this code down and make it clearer what is going on:

print $obj->{$foo->bar->baz}

And a working example:

  class foo {

    var $bar;

    function __construct() {

      // do something with a database to set $this->bar
      $this->bar = 'foobaz';
    }
  }

  $my_foo = new foo();
  $baz->foobaz = 'I am bar, called dynamically';

  print $baz->{$my_foo->bar};