PHP Reference Note Summary

Source: Internet
Author: User
Tags php template
This time to everyone to bring a summary of the PHP reference Note, PHP reference notes are what, the following is the actual case, together to see.

Objective

I took part in a number of meetings last year, eight of which I spoke about, many times I talked about PHP citations, because many people have a bias in understanding it. Before we delve into this issue, let's review the basic concepts of references and make clear what "reference passing" is.

Referencing in PHP means accessing the same variable content with a different name, regardless of which name you use to make the variable, and the contents of the other name's access will change.

Let's use the code to deepen our understanding of this. First we write a few simple statements, assign a variable to another variable, and change another variable:

<?php$a = $b = $a; $b = 42;var_dump ($a); Int (var_dump) ($b); Int (42)

The script shows that the $a value is still 23, while $b equals 42. The reason for this is that we get a copy of what happened later on ... Now we use references to do the same thing:

<?php$a = $b = & $a; $b = 42;var_dump ($a); Int (var_dump) ($b); Int (?>)

Now the value of $a has also changed to 42. In fact, there is no difference between $a and $b, both of which use the same variable container (AKA: Zval). The only way to separate the two is to use the unset () function to destroy any one of the variables.

In PHP, references can be used not only in ordinary statements, but also in function parameters and return values:

<?phpfunction &foo (& $param) {$param =; return $param;} $a = 23;echo "\ $a before calling Foo (): $a \ n"; $b = foo ($a); echo "\ $a after the call to Foo (): $a \ n"; $b = 23;echo "\ $a afte R touching the returned variable: $a \ n ";? >

What do you think the above results are? --yes, just like this:

$a before calling Foo (): 23$a after the call to Foo (): 42$a after touching the returned variable:42

Here we initialize a variable and pass it as a reference parameter to a function. The function changes it, and it has a new value. The function returns the same variable, we changed the returned variable and its original value ... Wait a minute! It doesn't change, does it? --yes, that's the way to cite it. The following happens: The function returns a reference, references a $a variable container zval, and creates a copy of it with the = assignment operator.

To fix this problem, we need to add an extra & operator:

$b = &foo ($a);

The result is the same as we expected:

$a before calling Foo (): 23$a after the call to Foo (): 42$a after touching the returned value:23

To summarize: PHP references are aliases to the same variable, and it can be difficult to use them correctly. To learn more about reference counting, here's a basic piece of information, see the reference Counting basics in the manual.

The biggest change when PHP 5 was released was the "Object handling method". Generally we understand that:

In PHP 4, objects are treated as variables, so they are copied when the object is passed as a function parameter. In PHP 5, however, they are always "referenced".

The above understanding is not entirely correct. The main purpose is to follow the "object pattern": When an object is passed to a function or method, the function sends an instruction to the object (such as invoking a method) to change the state of the object (such as the object's properties). So the object to be passed in must be the same. PHP 4 faces the target user to solve this problem by using "reference", but it is difficult to be perfect. PHP 5 introduces an "Object memory" that is independent of the variable container. When an object is assigned to a variable, the variable no longer stores the entire object (the property sheet and other "class" information), but rather a reference to the memory where the object resides-when we copy an object variable, we copy the "Memory Reference". This can easily be misunderstood as "references", but "Memory references" and "references" are completely different concepts. The following sample code helps us to better differentiate:

<?php//creates an object and a reference variable of this object $ A = new Stdclass; $b = $a; $c = & $a;//action on "object" $a->foo = 42; Var_dump ($a->foo); Int (var_dump) ($b->foo); Int (var_dump) ($c->foo); Int (42)//Now directly change the type of variable $ A = 42;var_dump ($a); Int (var_dump) ($b); Object (StdClass) #1719 (1) {    //   ["foo"]=>    //   int    ///}var_dump ($c);//int?>

In the above code, modifying the properties of an object affects the copied variable $b and the referenced variable $c. But in the code of the last chunk, when we modify the type of the $a, the $c of the reference changes, and the copied variable $b does not change, which is what most of the engineers with the object-faced experience expect.

So, facing the object is the only reason to use "references", but now PHP 4 is dead, you can also discard such usage.

Another reason for people to use "references" is--this will make the code faster. But this is wrong, the reference does not make the code execute faster, and worse, many times the "reference" will make your code execution less efficient.

I have to emphasize it once more: Yes, a lot of times "referencing" will make your code execution less efficient.

Other language engineers, who read other language coding specifications, will see suggestions for handling large data structures or strings, using pointers to reduce memory consumption to improve operational efficiency. These engineers mistakenly understand this concept to "references", whereas "pointers" and "references" are completely different technical models. PHP parser is different from other languages, in PHP, we use the "copy-on-write (Copy-on-write)" model.

In the copy-on-write model, assignment and function parameters do not trigger the copy action, and you can understand that many different variables point to the same "variable container", which triggers the copy action only when the write action occurs. This means that even if a variable appears to be "duplicated", it is not in essence. So when a large variable is passed to a function, it does not have much effect on performance. But at this point, if you use a reference to the argument, the reference to turn off the "copy-on-write" mechanism, which will lead to those who do not use the reference to pass the event is immediately copied one copy. This is not the end of the world, you can also be quoted everywhere in the line. This is not true: the internal mechanism of PHP relies on the "copy-on-write" model, and there are many internal function parameters that you cannot modify.
I have seen a code like this in some places:

<?phpfunction foo (& $data) {for ($i = 0; $i < strlen ($data); $i + +) {  do_something ($data {$i});}} $string = "... looooong string with lots of data ..."; foo (string); >

Obviously, the first problem with this piece of code is to call Strlen () in the loop instead of using the length that has been calculated. This means that the call to Strlen ($data) is possible, but he calls it many times. Unlike languages such as C, in general, PHP strings have their own lengths, so they do not have to be computed in length. So as far as strlen () is concerned, it's not too bad. But now another problem is that the developer of the case has passed a reference as a parameter to show his cleverness in order to save time. However, strlen () expects to get a copy. "Copy on Write" cannot be used for reference, so $data will be copied at strlen () call, strlen () will do an absolutely simple operation-in fact strlen () is one of the simplest functions in PHP-and the copy will be destroyed immediately.

If you do not use a reference, there is no need for a copy operation, and code execution is faster. And even if strlen () supports references, you won't get any more benefits.

Overall:

    • In addition to the legacy issues of PHP4, do not use references in object-oriented (OO).

    • Do not use references to improve performance.

The third problem with referencing to accomplish things is that the bad API design that results from the data being returned by a reference to the parameter. The problem is because the developer didn't realize that "PHP is PHP and not other languages".

In PHP, the same function can return different data types. --so you can return a string when the function executes successfully, and return a Boolean value on Failure false,php also allows complex struct types to be returned, such as arrays and objects. So when you need to return a lot of things, you can pack them together. In addition, exceptions are also a way for a function to return.

The use of references is a bad thing, except the fact that the reference itself is not good and the performance is degraded, using this method of referencing makes the code difficult to maintain. A function call like this code:

Do_something ($var);

Do you want $var to change? --Of course not. However, if the argument passed by Do_something () is a reference, it may change.

Another problem with such APIs is that functions cannot be chained, so you will always encounter scenarios where you must use temporary variables. Chained calls can make readability less readable, but in many scenarios, chained calls make the code more concise.

One of my favorite examples of bad design decisions about references is the sort () function that comes with PHP. Sort () uses an array as the reference parameter, and then returns a well-ordered array by reference. It might be better to return a well-ordered array by value as usual. Of course, this is due to historical reasons: sort () appears earlier than "Copy on write". "Copy-on-write" is generated in PHP4, and sort () is earlier, and it's early in PHP or as a convenient thing to do on the Web, rather than being a real language.

In short: In PHP, references are bad. Do not use references. They only get into trouble, and don't be hopeful about using references to boost the engine.

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

PHP State mode Use detailed

Php Template Method Pattern use detailed

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.