Possible Duplicate:
Reference - What does this symbol mean in PHP?
hi i have trouble to understand some of the & operator usage. i have come across with multiple examples and point out only those whitch i dont know what they really do ...
what does it mean when i'm:
1) using & in function name
function &foo() {}
2) using & in function parameter
function foo($id, &$desc) {}
3) usgin & in loop
foreach ($data as $key => &$item) {}
PHP(short for Hypertext PreProcessor) is the most widely used open source and general purpose server side scripting language used mainly in web development to create dynamic websites and applications.
The use keyword has two purposes: it tells a class to inherit a trait and it gives an alias to a namespace.
Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.
function &foo() {}
Returns a variable by reference from calling foo()
.
function foo($id, &$desc) {}
Takes a value as the first parameter $id
and a reference as the second parameter $desc
. If $desc
is modified within the function, the variable as passed by the calling code also gets modified.
The first two questions are answered by me in greater detail with clearer examples here.
And this:
foreach ($data as $key => &$item) {}
Uses foreach
to modify an array's values by reference. The reference points to the values within the array, so when you change them, you change the array as well. If you don't need to know about the key within your loop, you can also leave out $key =>
.
The PHP manual has a huge section on references (the & operator) explaining what they are and how to use them.
In your particular examples:
1) Is a return by reference. You need to use the & when calling the function and when declaring it, like you have above: Return by Reference
2) Is passing a parameter by reference. You only need to use the & in the function definition, not when calling the function: Passing by Reference
3) Is using a reference in a foreach loop. This allows you to modify the $item value within the originating array when you're inside the loop.
All the complete information on PHP references is available in the manual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With