php objects and references

伊谢尔伦
Release: 2016-11-23 13:49:15
Original
953 people have browsed it

A key point often mentioned in object programming in php5 is that "objects are passed by reference by default". But actually this is not entirely correct. Here are some examples to illustrate.

PHP references are aliases, that is, two different variable names point to the same content. In PHP5, an object variable no longer holds the value of the entire object. Just save an identifier to access the real object content. When an object is passed as a parameter, returned as a result, or assigned to another variable, the other variable has no reference relationship with the original one, but they both store a copy of the same identifier, which points to the real content of the same object. .

Example #1 References and objects

<?php
    class A {
        public $foo = 1;
    }
    $a = new A;
    $b = $a; // $a ,$b都是同一个标识符的拷贝
    // ($a) = ($b) = <id>
    $b->foo = 2;
    echo $a->foo."\n";
    $c = new A;
    $d = &$c; // $c ,$d是引用
    // ($c,$d) = <id>
    $d->foo = 2;
    echo $c->foo."\n";
    $e = new A;
    function foo($obj) {
        // ($obj) = ($e) = <id>
        $obj->foo = 2;
    }
    foo($e);
    echo $e->foo."\n";
?>
Copy after login

The above routine will output:

2
2
2
Copy after login


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template