The difference between PHP value passing and reference passing

Source: Internet
Author: User

Value passing (Sample demo)

1<?PHP2 //value passing: Within the scope of the function, changing the value of a variable is not likely to affect the values of the variables outside the function.3 functionTest$i){4     $i++;//variable i self-increment plus 15     $a=$i;//variable I assigns a value to the variable a6     return $a;//return variable a7 }8 9 $i= 5;//Define variable iTen Echo $i.‘ <br> ';//Output: 5 One EchoTest$i).‘ <br> ';//Output: 6 A Echo $i;//Output: 5

Reference Delivery (Sample demo)

1<?PHP2 //reference passing: Within the scope of the function, any change to the value is also reflected outside the function, because the pass-through reference is a memory address.3 functionTest (&$i){4     $i++;//variable i self-increment plus 15     $a=$i;//the reference to the variable i is passed to the variable a6     return $a;//return variable a7 }8 9 $i= 5;//Define variable iTen Echo $i.‘ <br> ';//Output: 5 One EchoTest$i).‘ <br> ';//Output: 6 A Echo $i;//Output: 6

Application Scenarios:

(1) When the value is passed, PHP must copy the value.

(2) Reference passing does not require copying values, so reference passing is generally used for large strings or objects.

Advantages and Disadvantages

(1) Passing values can be time consuming, especially for large strings and objects, which can be a costly operation.

(2) Transfer reference, any operation within the function is equivalent to the operation of the transfer variables, the transfer of large variables of high efficiency.

The difference between PHP value passing and reference passing

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.