Aspire Acer
Aspire Acer

Reputation: 47

How PHP variable variables work?

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

Answers (3)

Reyn
Reyn

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

dsgriffin
dsgriffin

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

Stegrex
Stegrex

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

Related Questions