Home  >  Article  >  Backend Development  >  Code example of method returning reference type in php

Code example of method returning reference type in php

怪我咯
怪我咯Original
2017-07-14 14:36:341195browse

Reference of php (that is, adding the & symbol in front of a variable, function, object, etc.) //The most important thing is to delete the variable referenced by , but the referenced variable cannot be accessed. But the content is not destroyed. The meaning of reference in PHP is: different names access the same variable content.

This article mainly introduces the method of returning reference type in PHP,

<?php
 
$color = &#39;YellowGreen&#39;;
 
function &getRef() {
    global $color;
    return $color;
}
 
function getCopy() {
    global $color;
    return $color;
}
 
$colorRef = &getRef();
$colorRef = &#39;Blue&#39;;
 
//$colorCopy = getCopy();
//$colorCopy = &#39;Black&#39;;
 
 
var_dump($color);
var_dump($colorRef);
//var_dump($colorCopy);

Run the above code once, and you will almost understand that using &getRef() will bind $colorRef to $color, which means that $colorRef and $color variables point to 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 behavior 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 another 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.

The above is the detailed content of Code example of method returning reference type in php. For more information, please follow other related articles on the PHP Chinese website!

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