What does =& mean in PHP?

前端 未结 3 1143
半阙折子戏
半阙折子戏 2020-12-03 07:17

Consider:

$smarty =& SESmarty::getInstance();

What is the & for?

相关标签:
3条回答
  • 2020-12-03 07:53

    It passes by reference. Meaning that it won't create a copy of the value passed.

    See: http://php.net/manual/en/language.references.php (See Adam's Answer)

    Usually, if you pass something like this:

    $a = 5;
    $b = $a;
    $b = 3;
    
    echo $a; // 5
    echo $b; // 3
    

    The original variable ($a) won't be modified if you change the second variable ($b) . If you pass by reference:

    $a = 5;
    $b =& $a;
    $b = 3;
    
    echo $a; // 3
    echo $b; // 3
    

    The original is changed as well.

    Which is useless when passing around objects, because they will be passed by reference by default.

    0 讨论(0)
  • 2020-12-03 07:55

    In PHP 4, it kind of (awkwardly) associated two variables.

    $j = 'original';
    $i =& $j;
    $i = 'modified';
    echo $j; // The output is 'modified'
    

    Likewise...

    $j = 'original';
    $i =& $j;
    $j = 'modified';
    echo $i; // The output is 'modified'
    

    Some of this was made a little less unpleasant when it comes to objects in PHP 5, but I think the heart of it is the same, so these examples should still be valid.

    0 讨论(0)
  • 2020-12-03 08:05

    References are used to alias variables and were necessary to use the old object system efficiently.

    In PHP 4, objects behaved like any other value type, that is, assignment would create a copy of the object. If you wanted to avoid this, you had to use a reference as in your example code.

    With PHP 5, object variables no longer contain the object itself, but a handle (AKA object identifier) and assignment will only copy the handle. Using a reference is no longer necessary.

    0 讨论(0)
提交回复
热议问题