2012-11-19 103 views
2

我有这样的代码:PHP - 动态参考对象属性

$result = $object->property[0]; 

,但我想要做的事,如:

if ($a) { 
    $property = 'blue' } 
else { 
    $property = 'black'} 
$result = $object->$property[0]; 

然而,这给我一个Cannot use string offset as an array错误。

任何指针(没有双关语意)感激。

+1

在'$属性删除前导''$ [0];' –

回答

6

使用括号:

$result = $object->{$property}[0]; 
0

$结果= $对象 - > {$属性}