PHP中的变量对象属性

时间:2015-04-12 20:16:40

标签: php

我有一个对象$var,它有3个属性one two three。我试图将属性存储在数组$info中。

漫长的道路:

$info['one'] = $var->one;
$info['two'] = $var->two;
$info['three'] = $var->three;

在未来的某个时刻,3个属性将变得更多,所以我试图使用foreach循环将属性存储在我的数组中。

$attributes = array( 'one', 'two', 'three' );

foreach ( $attributes as $attribute ) {
    $info[$attribute] = $var->$attribute; // My problem is here
}

我遇到的问题是你不能这样做:$var->$attribute

如何将变量用于我对象的属性?

1 个答案:

答案 0 :(得分:1)

您当前的代码运行正常,或者我会这样做:

$var = new someObj;
$attributes = array( 'one', 'two', 'three' );
$info = array_intersect_key(array_flip($attributes), get_object_vars($var));
相关问题