henrywright
henrywright

Reputation: 10240

Variable object properties in PHP

I have an object $var which has 3 properties one two three. I'm trying to store the properties in an array $info.

The long way:

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

At some point in the future the 3 properties will become many more so I'm trying to store the properties in my array using a foreach loop.

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

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

The problem I'm having is you can't do this: $var->$attribute.

How can I use a variable for my object's property?

Upvotes: 1

Views: 63

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

Your current code works fine, or I would just do:

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

Upvotes: 1

Related Questions