1

How can I access values from an object property that is an array?

For example:

$myObject = new MyClass;

$myObject->myproperty = array(1 => 'English', 2 => 'French', 3 => 'German');

How can I get individual property values using the array keys from $myObject->mypropery? Using $myObject->myproperty[3] does not work.

EDIT: Using $myObject->myproperty[3] does in fact work. Where I find a problem is when doing it like this:

$myproperty = 'myproperty';

echo $myObject->$myproperty[3]

// result : 'r'

Yet if I do a var_dump on $myObject->$myproperty I see my array.

1
  • $myObject->$myProperty will take the value from $myProperty and use it as the property name. So if $myProperty = 'foo';, then it would be the same as saying $myObject->foo. Commented Dec 25, 2012 at 0:23

3 Answers 3

1

try this:

$myObject->myproperty[3]

instead of this:

$myObject->$myproperty[3]
Sign up to request clarification or add additional context in comments.

1 Comment

Naturally, I already answered that, however this is for a behavior that can apply to a multitude of classes, thus $myObject->$myProperty is essential
0

To access your myproperty array values try this:

$myObject->{$myproperty}[3]

Instead of:

$myObject->$myproperty[3]

These are referred to as Variables Variable, for more information visit: http://php.net/manual/en/language.variables.variable.php

The reason your echo result was r is because your $mypropery value is mypropery and you executed this echo $myObject->$myproperty[3] which translate to saying you want the third character array keys value. Since arrays are zero based this means you will get the character r as a result. Hope this clears up why your result was r.

1 Comment

Yes, I understood that's exactly why I was getting 'r'. Your answer is entirely correct. I had tried the same previously, but due to some other logical error it didn't work. Have tried again and it does. Thank you!
0
$tmp = $myObject->$myproperty;
echo $tmp[1];
//or
echo $myObject->{$myproperty}[1];

Comments

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.