What does & in &$data do?
A quick beginner's question in PHP.
What does & in &$data do and what are differences with $data?
function prepareMenu(&$data) {
$开发者_如何学JAVAthis->db->where('parentid',0)
...
...
&$data
is passed by reference, $data
is passed by value
Passed by reference - you are passing a reference to the object, not copy. You are using the same object in the caller.
passed by value - you copy the object and pass it to the function. You are working with a copy of the object, different from the object in the caller.
An example of what the result of this is, would be, if you ran the following program:
$data = 3;
print($data);
prepareMenu($data);
print($data);
function prepareMenu(&$data)
{
$data = 7;
print($data);
}
You would get the output:
3
7
7
Whereas if you passed by value, rather than by reference:
$data = 3;
print($data);
prepareMenu($data);
print($data);
function prepareMenu($data)
{
$data = 7;
print($data);
}
You would get the output:
3
7
3
As in the second example, the value in $data would be copied for use in prepareMenu, as opposed to the first example where you're always working with the original $data
Note: Haven't written PHP in years, so don't expect this to actually compile, it's meant as an example only =)
The & in &$data marks it as a reference.
http://docs.php.net/references explains how they work in php.
In the simplest terms I can muster:
& - Pass By Reference
Passing a variable by reference means you are passing a copy of the memory address the variable uses to store it's data. PHP has an entire section on their website dedicated to explaining this entitled "References Explained".
This simply means that you can modify the original variable from a secondary source.
Example
function testFunction(&$param) {
$param = 'test2';
}
$var = 'test';
echo $var; // outputs 'test'
testFunction($var);
echo $var; // outputs 'test2'
精彩评论