user3869069
user3869069

Reputation: 45

Variable variables concept confusion

Hey guys am a newbie in PHP. I have seen some code like:

<?php
class foo {
    var $bar = 'I am bar.';
    var $arr = array('I am A.', 'I am B.', 'I am C.');
    var $r = 'some';
}

$foo = new foo();
$arr = 'arr';
echo $foo->$arr[1];
?>

It returns some. Why it is returning some. echo $foo->$arr[1] means it should output I am B. But instead it outputs some; why?

Upvotes: 0

Views: 44

Answers (2)

dave
dave

Reputation: 64657

When you access a property of a class, you don't use $ before the property. If you do, it will evaluate that portion first, to figure out what property to access.

echo $foo->$arr[1];

$arr is 'arr', so when you access it as an array, it will grab the letter at whatever index you specify.

$arr[1] is "r";

$foo->r = 'some';

If you access the object property without the $:

echo $foo->arr[1];

it will output I am B.

As a side note, if you DO want to use variable-variables, and it's an array, you should really use parenthesis.

$foo->$arr[1];

is ambiguous as to whether you mean

($foo->$arr)[1];

or

$foo->($arr[1]);

Upvotes: 5

pan85
pan85

Reputation: 61

Try,

   <?php
       class foo {
         public $bar = 'I am bar.';
         public $arr = array('I am A.', 'I am B.', 'I am C.');
         public $r = 'some';
       }

       $foo = new foo();
       echo $foo->arr[1];
   ?>

To access object variable have to use $foo->var_name;

Upvotes: 0

Related Questions