8

What is the explanation for the following syntax?

$var1->$var2 // Note the second $
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
eft
  • 2,509
  • 6
  • 26
  • 24

3 Answers3

18

You are calling a property on $var1 that is named the same as the value of $var2.

For example:

$var2 = "name";

// The following are equivalent
$var1->name;
$var1->$var2;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
10

$var1 is an object.

$var2 is (possibly) the name of a variable inside $var1.

If $var2="test"; this is evaluated to:

$var1->test;

You can do this with all sorts of things:

$test = array();
$name="test";
print_r($$name); // Prints array();

$test = new stdClass;
$test->hello = "hi";
$name2="hello";
echo $test->$name2; // Echos hi

You can even get really fancy:

echo $$name->$name2; // Echos hi
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
  • 1
    What's with the double dollar signs? – CodyBugstein Mar 17 '13 at 22:18
  • Can you include an example of a get/post with an else? – i am me Nov 07 '15 at 20:27
  • @CodyBugstein if `$foo="bar"` and `$bar="biz"` then `$$foo` will return `"biz"` because the double dollar sign will tell the computer to get the variable whose name is the value of `foo`. Basically, in `$$foo`, replace in your head `$foo` with `bar` and you get `$bar`. Note the `$` in `$bar`is the first `$` in `$$foo` which remains after you replaced it in your head. http://stackoverflow.com/questions/2715654/what-does-dollar-dollar-or-double-dollar-mean-in-php – Abraham Murciano Benzadon May 16 '17 at 15:13
2

It means dynamically query a property in an object.

class A {
  public $a;
}

// static property access
$ob = new A;
$ob->a = 123;
print_r($ob);

// dynamic property access
$prop = 'a';
$ob->$prop = 345; // effectively $ob->a = 345;
print_r($ob);

so $var1 is an instance of some object, -> means access to a member of that object and $var2 contains the name of a property.

cletus
  • 616,129
  • 168
  • 910
  • 942