2

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;

2 Answers 2

1

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'));
Sign up to request clarification or add additional context in comments.

1 Comment

in my opinion this is a very elegant solution! thanks for sharing. accepted answer
1

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

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

echo $test->$access_property1->$access_property2;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.