Reputation: 12957
Below is the text from PHP Manual :
PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object.
A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an 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.
After going through the above text I've following doubts in my mind:
How all of the above entities function?
Can someone please clear the doubts I have in an easy to understand, simple and lucid language in short and step-by-step manner?
It would be great if someone can explain these concepts with some suitable, working code example having explanatory comments at appropriate places in the code.
If possible, someone can also explain with the help of pictorial representation of working of these concepts. It would be highly appreciated.
You can take up following example or specify your own suitable example to explain all of the above concepts.
<?php
class A {
public $foo = 1;
}
$a = new A;
$b = $a;
$b->foo = 2;
echo $a->foo."\n";
$c = new A;
$d = &$c;
$d->foo = 2;
echo $c->foo."\n";
$e = new A;
function foo($obj) {
$obj->foo = 2;
}
foo($e);
echo $e->foo."\n";
?>
Thank You.
Reference links from the PHP Manual :
Upvotes: 1
Views: 233
Reputation: 781078
Object
is an instance of a class that you create with new Classname
.Object Reference
is a PHP variable whose value is an Object
.Object Identifier
is a value internal to the PHP implementation that identifies a particular object. It's probably something like an index into an array that contains pointers to all the objects.Object accessors
are operations that access the contents of objects, such as $d->foo
.This is all just implementation details for how you can have multiple variables referring to the same object without having to use reference variables explicitly.
$a = new A;
$b = $a;
$a->foo = 2;
echo $b->foo; // echoes 2
The assignment isn't making a copy of the object, it's just copying the object identifier. All copies of an object identifier refer to the same object. Think of it like a pointer in languages like C or C++ -- when you copy a pointer, both variables refer to the same memory.
To make a copy of an object, you have to use clone
.
$c = clone $a;
This is different from how arrays work, which is that assignment makes a copy, unless you use an explicit reference variable. (As an optimization, PHP uses copy-on-write, so it doesn't actually copy the array memory unless you modify it.)
$x = array(1);
$y = $x;
$z = &$x;
$x[0] = 2;
echo $y[0]; // echoes 1
echo $z[0]; // echoes 2
Upvotes: 2