This is an extended explanation of the examples on Object Assignment (example 19-5) from OOP5 Basics on the PHP Manual.

The full script can be accessed here

First we create the simple class from the example.


class SimpleClass {
	//member declaration
	public $var = 'default value';
	//method declaration
	public function displayVar() {
		echo $this->var;
	}
}

Creating a New Instance


$instance = new SimpleClass();

What exactly does this do?. It Allocates an space in memory for this new object and then references the variable $instance to this space in memory (representing the instance of the object).

Instance equals new object Graph

Assigning a Variable to an already created object


$assigned = $instance;

References the variable $assigned to the object in memory referenced by $instance.

Assigned equals instance Graph

Referencing a Variable to a variable that references an object


$reference &= $instance;

References the variable $reference not to the object in memory referenced by $instance but to the variable $instance itself.

Reference references instance Graph

Cloning an object


$cloned = clone $instance

Allocate in memory space for a new instance of the Object. Copy all the values from the instance referenced by $instance. References the variable $cloned to this new instance of the object in memory.

Cloned clones instance Graph

Full Picture up to now

If we dump with var_dump all of this (see script). We get the following:

Instance: object(SimpleClass)#1 (1) { ["var"]=>  string(13) “default value” }
Assigned: object(SimpleClass)#1 (1) { ["var"]=> string(13) “default value” }
Referenced: object(SimpleClass)#1 (1) { ["var"]=> string(13) “default value” }
Cloned: object(SimpleClass)#2 (1) { ["var"]=> string(13) “default value” }

A good graphical representation of this is:

PHP 5Object Assignment Script State 1

Changing the value of a Member and then Dereferencing $Instance

Now, we’ll do a couple of changes so as to make all of this even clearer.


//Change variable in instance (will be changed in all but cloned)
$instance->var = 'New value';

//Derefence $instance.
$instance = NULL;

What we have just done is change the value of the member var in Obj 1 and then derefencing $instance to obj1.

Instance equals null Graph

Full Final Picture of the script

Let’s see what happens now when we dump all of the variables (see script). Results:

Instance: NULL
Reference: NULL
Assigned: object(SimpleClass)#1 (1) { ["var"]=> string(9) “New value” }
Cloned: object(SimpleClass)#2 (1) { ["var"]=> string(13) “default value” }

A graphical representation of the final state of our script:

PHP 5Object Assignment Script State 2