开发者

PHP Access sub property by name at runtime

开发者 https://www.devze.com 2022-12-17 17:22 出处:网络
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.

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;


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'));


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

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

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

精彩评论

暂无评论...
验证码 换一张
取 消