Home  >  Article  >  Backend Development  >  "e in php

"e in php

WBOY
WBOYOriginal
2016-08-18 09:16:06938browse

In some frameworks, you sometimes see variables of type &$arr on functions. After searching online, I only found 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, you sometimes see variables of type &$arr on functions. After searching online, I only found 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 the original value needs to be changed, for example, I have a function that needs to output several values,

The questioner should know that php can only return one value, of course you can use array packaging

<code><?php
function test(&$a,&$b){
    $a = 1;
    $b = 1;
}

test($a,$b);
echo $a,"@",$b;</code>

You can see the output

<code>1@1</code>

Another situation is that when a large array is used, a memory copy can be omitted to save memory overhead

<code class="php">$a = "china";
$b = &$a;</code>
In this way, PHP only needs to store one copy of data. Therefore, when programming, large variables generally need to be passed by reference to save memory resources. In PHP function parameter calls, objects are passed by reference by default.

What you want to ask is

<code>function (&$arr) {}
</code>

Is this how to use it?

This thing is used to modify the variable $arr itself. Because the function is a closed space, if you change $arr in the function, the variables outside will not change. You can use this if you don't want to use

return

to return the changed variable. For example

bool asort (array &$array [, int $sort_flags = SORT_REGULAR])
This function, you can see that the return value is bool type, but it can also return a modified array. This is done using the & reference symbol.

Because the default value passed by an array is completely different from that of an object. Passing a value will make a copy, and unlike things like integers and floating points, arrays have a lot of content and the overhead caused by copying is very high, so it is generally forced to pass a value.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn