Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

try this:

$myObject->myproperty[3]

instead of this:

$myObject->$myproperty[3]
$tmp = $myObject->$myproperty;
echo $tmp[1];
//or
echo $myObject->{$myproperty}[1];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top