2010-01-16 43 views
2

是否可以動態訪問對象的子屬性?我管理它來訪問一個對象的屬性,但不是一個子對象的屬性。PHP在運行時按名稱訪問子屬性

這裏是我想要做的事情的例子:

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; 

回答

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

在我看來這是一個非常優雅的解決方案!感謝分享。接受的答案 – 2010-01-16 15:03:30

1

我不這麼認爲...但是你可以這樣做:

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

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