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

后端 未结 3 2040
半阙折子戏
半阙折子戏 2020-12-18 01:43

What is the explanation for the following syntax?

$var1->$var2 // Note the second $
3条回答
  •  感动是毒
    2020-12-18 02:27

    $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
    

提交回复
热议问题