First, sorry for the stupid question, but I was reading an article in php.net and I couldn't understand what exactly it says.
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
<?php
$instance = new SimpleClass();
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned will have this value';
$instance = null; // $instance and $reference become null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
And this outputs this:
NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value"
}
$instance and $reference point to same place, I get this and I understand why we get NULL and NULL for them.
But what about $assigned? It's it also pointing the place where $instance is stored? Why when we use $instance->var
it affects $assigned, but when we set $instance to be null, there is no change for $assigned?
I thought that the all three variables point to one place in the memory, but obviously I'm wrong. Could you please explain me what exactly happens and what is $assigned? Thank you very much!
An Object is an individual instance of the data structure defined by a class. We define a class once and then make many objects that belong to it. Objects are also known as instances.
In PHP, Object is a compound data type (along with arrays). Values of more than one types can be stored together in a single variable. Object is an instance of either a built-in or user defined class. In addition to properties, class defines functionality associated with data.
Objects of a class is created using the new keyword.
In PHP, objects are passed by references by default. Here, reference is an alias, which allows two different variables to write to the same value. An object variable doesn't contain the object itself as value. It only contains an object identifier which allows using which the actual object is found.
$reference
points to the value of $instance
, which is itself a reference to an object. So when you change the value contained by $instance
, $reference
reflects this change.
$assigned
, on the other hand, is a copy of the value of $instance
, and independently points to the object itself to which $instance
refers. So when the value $instance
is updated to point to nothing (i.e. null
), $assigned
is not affected, since it still points to the object, and doesn't care about the contents of $instance
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With