How does the '&' symbol in PHP affect the outcome?

混江龙づ霸主 提交于 2019-11-30 15:50:30

问题


I've written and played around with alot of PHP function and variables where the original author has written the original code and I've had to continue on developing the product ie. Joomla Components/Modules/Plugins and I've always come up with this question:

How does the '&' symbol attached to a function or a variable affect the outcome?

For instance:

$variable1 =& $variable2;

OR

function &usethisfunction() {
}

OR

function usethisfunction(&thisvariable) {
{

I've tried searching through the PHP manual and other related sources but cannot find anything that specifically addresses my question.


回答1:


These are known as references.

Here is an example of some "regular" PHP code:

function alterMe($var) {
    $var = 'hello';
}

$test = 'hi';
alterMe($test);
print $test; // prints hi

$a = 'hi';
$b = $a;
$a = 'hello';
print $b; // prints hi

And this is what you can achieve using references:

function alterMe(&$var) {
    $var = 'hello';
}

$test = 'hi';
alterMe($test);
print $test; // prints hello

$a = 'hi';
$b &= $a;
$a = 'hello';
print $b; // prints hello

The nitty gritty details are in the documentation. Essentially, however:

References in PHP are a means to access the same variable content by different names. They are not like C pointers; instead, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The closest analogy is with Unix filenames and files - variable names are directory entries, while variable content is the file itself. References can be likened to hardlinking in Unix filesystem.




回答2:


<?php

$a = "hello";   # $a points to a slot in memory that stores "hello"
$b = $a;        # $b holds what $a holds

$a = "world";
echo $b;        # prints "hello"

Now if we add &

$a = "hello";   # $a points to a slot in memory that stores "hello"
$b = &$a;   # $b points to the same address in memory as $a

$a = "world";

# prints "world" because it points to the same address in memory as $a.
# Basically it's 2 different variables pointing to the same address in memory
echo $b;        
?>



回答3:


It is a reference. It allows 2 variable names to point to the same content.



来源:https://stackoverflow.com/questions/999333/how-does-the-symbol-in-php-affect-the-outcome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!