开发者

What does the PHP syntax $var1->$var2 mean?

What is the explanation for the following syntax?开发者_如何学运维

$var1->$var2 // Note the second $


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;


$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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜