views:

71

answers:

2

Hello!

Is it possible to access a sub-property of an object dynamically? I managed it to access the properties of an object, but not the properties of a sub-object.

Here is an example of the things I want to do:

class SubTest
{
    public $age;

    public function __construct($age)
    {
        $this->age = $age;
    }
}

class Test
{
    public $name;
    public $sub;

    public function __construct($name, $age)
    {
        $this->name = $name;
        $this->sub = new SubTest($age);
    }
}

$test = new Test("Mike", 43);

// NOTE works fine
$access_property1 = "name";
echo $test->$access_property1;

// NOTE doesn't work, returns null
$access_property2 = "sub->age";
echo $test->$access_property2;

Thanks in advance!

+1  A: 

I don't think so... But you could do this:

$access_property1 = "sub";
$access_property2 = "age";

echo $test->$access_property1->$access_property2;
Alix Axel
+1  A: 

You could use a function like

function foo($obj, array $aProps) {
  // might want to add more error handling here
  foreach($aProps as $p) {
    $obj = $obj->$p;
  }
  return $obj;
}

$o = new StdClass;
$o->prop1 = new StdClass;
$o->prop1->x = 'ABC';

echo foo($o, array('prop1', 'x'));
VolkerK
in my opinion this is a very elegant solution! thanks for sharing. accepted answer
maxwell