1

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?

10
  • Why shouldn't you be able to do that? Do you get any errors? The code works fine for me. Commented Apr 12, 2015 at 20:17
  • 3
    Try $var->{$attribute} or I would just do $info = get_object_vars($var). Commented Apr 12, 2015 at 20:20
  • @Rizier123 are you saying I can do that? Commented Apr 12, 2015 at 20:24
  • @henrywright I would say that's the way to do it! (OR use ^ get_object_vars() as AbraCadaver mentioned) Commented Apr 12, 2015 at 20:25
  • 2
    @henrywright : what is Rizier123 saying is that, if what you show is the real word example, your snippet of code does work properly. If it does not, that means, you have another problem you are not showing us. Commented Apr 12, 2015 at 20:29

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

2 Comments

what's the difference between $var->{$attribute} and $var->$attribute?
On beer 5 I'm going to step away for now :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.