Differences between passing references in PHP array object values

Source: Internet
Author: User

The general data types (INT, float, bool) are not described in this regard.

Here we will introduce in detail the differences between the array and the class object passing values as parameters.

Array value transfer

Instance code:

<?phpfunction main() {        $cc = array(            'a','b'        );        change($cc);        var_dump($cc);        die;}function change($cc){        $cc = array('dd');}main();?>output:array(2) {  [0]=>  string(1) "a"  [1]=>  string(1) "b"}

Array reference Transfer

<?phpfunction main() {        $cc = array(            'a','b'        );        change($cc);        var_dump($cc);        die;}function change(&$cc){        $cc = array('dd');}main();?>outpout:array(1) {  [0]=>  string(2) "dd"}

 

Class Object value transfer

<?phpclass pp{        public $ss = 0;}function main() {        $p = new pp();        change($p);        var_dump($p);        die;}function change($p){        $p->ss = 10;}main();?>output:object(pp)#1 (1) {  ["ss"]=>  int(10)}

Class Object Reference Transfer

<?phpclass pp{        public $ss = 0;}function main() {        $p = new pp();        change($p);        var_dump($p);        die;}function change(&$p){        $p->ss = 10;}main();?>object(pp)#1 (1) {  ["ss"]=>  int(10)}

 Summary: in PHP, an array is a common variable. Passing a value requires a copy of a real parameter, which is irrelevant to the real parameter. After passing a reference, the value of the real parameter can be changed.
The object of the class is a reference transfer for both value passing and reference passing. It is a reference to the object and changes the value of the real parameter.

 

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.