PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Namespaces> <Clase şi Obiecte (PHP 5)
Last updated: Fri, 01 Aug 2008

view this page in

Objects and references

One of the key-point of PHP5 OOP that is often mentioned is that "objects are passed by references by default" This is not completely true. This section rectifies that general thought using some examples.

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains a object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

Example #1 References and Objects

<?php
class {
    public 
$foo 1;
}  

$a = new A;
$b $a;     // $a and $b are copies of the same identifier
             // ($a) = ($b) = <id>
$b->foo 2;
echo 
$a->foo."\n";


$c = new A;
$d = &$c;    // $c and $d are references
             // ($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";

?>

Exemplul de mai sus va afişa:

2
2
2


add a note add a note User Contributed Notes
Objects and references
There are no user contributed notes for this page.

Namespaces> <Clase şi Obiecte (PHP 5)
Last updated: Fri, 01 Aug 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites