从 PHP 数组中将对象作为变量拉出(在 Drupal 7 模块中)

Pull object as variable from PHP array (in Drupal 7 module)

希望我以一种有意义的方式提出这个问题。找不到任何可以回答这个问题的东西,尽管我可能没有正确地表达我的搜索词。

在我的 Drupal 7 自定义模块中,我能够使用以下对象运算符(箭头 ->)语法成功地从分类法数组中获取数据

$term = taxonomy_term_load($taxonomy_tid);
$description = $term->description;
echo $description;

如何使 "description" 标签本身成为一个变量?设置为:

$term = taxonomy_term_load($taxonomy_tid);
$description_name_from_array = 'description';
$description = $term->????;
echo $description;

不起作用的东西:

在特定情况下可能需要大括号,但您的第一次尝试应该可以访问 description。从对象访问简单变量 属性 的正确语法是

 $obj->$property

Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.

虽然用花括号封装变量以清楚地分隔 属性 名称更安全:

$obj->{$property}

需要当:

  • 访问包含数组的 属性 中的值:$obj->${$properties[0]}
  • 当 属性 名称由多个部分组成时:$obj->{$a . $b}
  • 当使用常量访问 属性 时:$obj->{CONSTANT_NAME}
  • 或者当 属性 名称包含无效的字符时

参见 PHP 的 Variable Variables