Difference between revisions of "ObjectsAndRefs"
From Hashphp.org
Line 1: | Line 1: | ||
+ | {{Stub}} | ||
+ | |||
This page attempts to provide a visual guide to how objects - and references to them - work in PHP 5.0 and later. | This page attempts to provide a visual guide to how objects - and references to them - work in PHP 5.0 and later. | ||
Revision as of 22:27, 27 July 2011
This article is a stub. You can help us by expanding it. |
This page attempts to provide a visual guide to how objects - and references to them - work in PHP 5.0 and later.
class SimpleClass { public $var = 'a default value'; } $instance = new SimpleClass(); |
|
The above code creates a new class, SimpleClass, with no properties or methods. It then creates a new instance of this class and attaches it to the variable named '$instance'. | |
---|---|
$assigned = $instance; | |
For example, when we assign the variable '$instance' to a new variable '$assigned', what we end up with is the one object with two different labels. | |
$instance->var = '$assigned will have this value as well'; | |
Even though we changed the property via the variable '$instance', it changed the underlying object, so both '$assigned' and '$instance' will have the new value. | |
$reference =& $instance; | |
'$reference', on the other hand, is a reference to the variable '$instance', and is NOT attached directly to the underlying object. | |
$instance = null; | |
So when we assign NULL into '$instance', we haven't changed the object (it's still available via '$assigned'), but both '$instance' and '$reference' have lost their attachment to it. |