In some frameworks, sometimes we can see variables of the & amp; $ arr type on the function. after searching online, we only know that this is a reference, I want to know under what circumstances we need to use this during development, what are the disadvantages of using this function? in some frameworks, sometimes we can see variables of the type & $ arr in the function. after searching online, we only know that this is a reference, I want to know under what circumstances we need to use this during development, and what are the disadvantages of using this?
Reply content:
In some frameworks, sometimes we can see variables of the type & $ arr in the function. after searching online, we only know that this is a reference, I want to know under what circumstances we need to use this during development, and what are the disadvantages of using this?
When you need to change the original value, for example, I have a function that needs to output several values,
The subject should know that php can return only one value. of course, you can use array packaging.
The output is displayed.
1@1
Another case is that a memory copy can be omitted when large arrays are used to save memory overhead.
$a = "china";$b = &$a;
In this way, php only needs to store a copy of data. therefore, during programming, large variables generally need to be referenced to save memory resources. in PHP function parameter calls, objects are referenced by default.
What you want to ask
function (&$arr) {}
In this way?
This is used to modify the variable $ arr itself. Because the function is a closed space, if you change $ arr in the function, the variable outside will not change. If you do not want to usereturnYou can use this variable to return the changed variable.
For example
bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
You can see that the returned value belongs to the bool type, but it can also return the modified array.
This is done with the reference symbol.
Because the default value of the array is different from that of the object. If the input value is a copy, and the array is not like an integer floating point, it has a lot of content and the overhead of the copy operation is large, so it is generally forced to pass the value.