PHP在运行时按名称访问子属性

时间:2010-01-16 13:34:18

标签: php oop class properties

是否可以动态访问对象的子属性?我管理它来访问对象的属性,但不访问子对象的属性。

这是我想要做的事情的一个例子:

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 个答案:

答案 0 :(得分:1)

我不这么认为......但你可以这样做:

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

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

答案 1 :(得分:1)

你可以使用像

这样的功能
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'));