Reputation: 47
I know how PHP variable variables works, but have trouble understanding why this script outputs "I am r." instead of "I am B."
<?php
class fooo {
var $bar = 'I am bar.';
var $arr = array('I am A.', 'I am B.', 'I am C.');
var $r = 'I am r.';
}
$fooo = new fooo();
$arr = 'arr';
echo $fooo->$arr[1] . "\n";
//above line output
//I am r.
?>
Upvotes: 3
Views: 124
Reputation: 757
To get the 'I am B'.
You need to resolve $arr first.
echo $fooo->${$arr}[1]
The reason being is the scope of the variable which is $arr='arr' not the property $arr=array
Upvotes: 0
Reputation: 68596
You are defining $arr = 'arr';
and then getting the second character from the string 'arr', not the array inside class Foo, that is why you are getting 'r' ([1]
returning the second character from your word).
The solution? you should replace:
echo $fooo->$arr[1] . "\n";
with:
echo $fooo->arr[1] . "\n";
You should receive your desired output:
'I am B.'
Upvotes: 5
Reputation: 4024
When you reference an object property, it's the name of the variable, not the variable itself. So you'll want to do:
echo $fooo->arr[1] . "\n";
To get what you expected.
Upvotes: 0