Ways to return reference types in PHP _php tips

Source: Internet
Author: User

Returns a reference that cannot be omitted at the time of definition and invocation &.

This is a more confusing concept and should not be used for specific reasons.

said that he is very easy to mix, because the Reference in the PHP5 change, causes it to behave in the PHP4/PHP5 behavior difference is quite big.

For an example:

Copy Code code as follows:

<?php

$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);

Running the code above, it almost becomes clear that using &getref () will bind $colorRef to the $color, which means $colorRef and $color two variables are pointing to the same value. When you change one of these values, the other changes as well.

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

When $color is an Object, the problem arises.

Getcopy still returns a replicated Object;&getref () return reference in PHP4.

PHP5 is a bit of a different kind,
The newest PHP5.2, behaves like PHP4, Getcopy () returns a copy, &getref () returns a reference.
But some of the PHP5 versions are slightly different here, such as PHP5.1.6, where Getcopy () and &getref () are references.

Here Getcopy () and &getref () are two global functions, and if placed inside the class as member functions of the class, it would be another scene ...

PS: Returning References does not improve performance, sometimes it degrades performance, so do not use this feature to "optimize" the program for granted.

There's a problem. See the manual most of the time you can find the answer:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.