0

在下面的示例中,我们有一个由空格分隔的单词组成的字符串。字符串中的每个单词将代表对象的嵌套级别。在实际实现中,我不会提前知道字符串。

$string = "Actor Name";
$object->Actor->Name = "John Doe";

function getValue($string, $object) {
   // do stuff
   return $value; // John Doe
}

另一个例子:

$string = "Actor Email";
$object->Actor->Email = "johndoe@example.com";

$value = getValue($string, $object); // johndoe@example.com
4

1 回答 1

2

遍历由空格分割的字符串:

$last = $object;
foreach (explode(' ', $string) as $piece) {
   $last = $last->$piece
}
return $last;
于 2012-12-03T05:17:10.517 回答