Home  >  Article  >  Backend Development  >  Methods that return reference types in PHP, php returns reference types_PHP tutorial

Methods that return reference types in PHP, php returns reference types_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:58:05769browse

Methods in PHP that return reference types. PHP returns reference types.

Return references. & cannot be omitted when defining or calling.

This is a relatively confusing concept. Unless it is for some special reasons, it is recommended not to use it.

It is said that it is easy to confuse because of the changes in Reference in PHP5, resulting in a relatively large difference in its behavior in PHP4/PHP5.

Give me an example:
Copy code The code is as follows:

$color = 'YellowGreen';

function &getRef() {
global $color;
Return $color;
}

function getCopy() {
global $color;
Return $color;
}

$colorRef = &getRef();
$colorRef = 'Blue';

//$colorCopy = getCopy();
//$colorCopy = 'Black';


var_dump($color);
var_dump($colorRef);
//var_dump($colorCopy);

Run the above code and you will almost understand that using &getRef() will bind $colorRef to $color, which means that the two variables $colorRef and $color point to the same value. When you change one of the values, the other will also change.

If $color is an array, the same is true. The above code will behave the same in any version of PHP4/5.

The problem arises when $color is an Object.

In PHP4, getCopy will still return a copied Object; &getRef() returns a reference.

PHP5 is a bit different,
The latest PHP5.2 behaves the same as PHP4, getCopy() returns copy, &getRef() returns reference.
But some PHP5 versions are slightly different here, such as PHP5.1.6, which shows that getCopy() and &getRef() are both references.

Here getCopy() and &getRef() are two global functions. If they are placed in a class and become member functions of the class, it will be a different story...

PS: Returning References will not improve performance, but sometimes it will reduce performance, so don't take it for granted to use this feature to "optimize" the program.

If you have any questions, you can usually find the answer by reading the manual:

http://cn.php.net/manual/en/language.references.php

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/978725.htmlTechArticleMethods in PHP that return reference types, php returns reference types and returns references, when defined and called
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