如何以编程方式从具有特殊语法的字符串派生嵌套对象字段的值?

In the following example, we have a string consisting of words separated by spaces. Each word in the string will represent a nesting level of an object. In actual implementation, I will not know the string ahead of time.

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

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

Another example:

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

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

Iterate over the string split by spaces:

$last = $object;
foreach (explode(' ', $string) as $piece) {
   $last = $last->$piece
}
return $last;