0

在特定情况下我需要帮助...

我想通过循环中的字符串访问对象的属性......并且该属性实际上是一个具有它自己的属性的对象ofcourse。

进一步来说,$object->$object->property;

一些不起作用的代码:

$objectAtribute = 'property->propertyOfObject';
echo $object->$objectAtribute;

怎么做到呢 !?

顺便说一句,我收到一个错误:未定义的属性

肿瘤坏死因子

4

2 回答 2

3

问题是您正在尝试访问一个实际称为property->propertyOfObject. 尝试打破它:

$className = 'className';
$object = new $className();

$propertyName = 'propertyName';
echo $object->$propertyName;

或者,如果您不想创建新变量:

echo $object->{'propertyName'};

如果您的对象的类实现ArrayAccess,那么您可以简单地使用

echo $object['propertyName'];
于 2013-05-05T20:20:50.150 回答
1
$objectProperty       = 'property';
$objectObjectProperty = 'propertyOfObject';

echo $object->$objectProperty->$objectObjectProperty;

'property->propertyOfObject' won't work without ugly eval tricks or manual "parsing", don't even get yourself down the road where you are even thinking about doing that. Then your code is too "dynamic" and punching the monkey too much.

于 2013-05-05T20:16:26.300 回答