3

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.
?> 
5
  • $arr inside the class belongs to the class (a property of it). When you set the $arr inside fooo() you do: $fooo->arr = 'arr';. The $arr you set now belongs to the normal scope and not the one inside the instanced object of the class fooo. Try to Google a bit on how scopes work in programming. It will become much more clearer :) Commented Mar 20, 2013 at 23:48
  • $arr inside the foo class is encapsulated and points different memory address from $arr variable points Commented Mar 20, 2013 at 23:49
  • 1
    @SamDufel and that helps him how? We don't all have the same level of skill or the same pace of learning. We should embrace people who are new to coding just as much as people with a lot experience and adjust our response to their skillset. Commented Mar 20, 2013 at 23:51
  • Apparently $fooo->$arr[1] is equivalent to $fooo->{$arr[1]} Commented Mar 20, 2013 at 23:54
  • 1
    @Allendar - my point was that it's an extremely obscure way to access a property. Constructs like that are OK if you're trying to test someone's knowledge a language, but it's also something you would never need to use. Furthermore, I wrote it as a comment, not an answer... Commented Mar 20, 2013 at 23:55

3 Answers 3

5

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

Comments

0

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.

Comments

0

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

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.