Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Assignment in PHP

Tags:

php

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!

like image 221
Faery Avatar asked Oct 19 '12 08:10

Faery


People also ask

What is object in PHP with example?

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.

What is object properties PHP?

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.

How do you create an object in PHP?

Objects of a class is created using the new keyword.

How are objects passed in PHP?

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.


1 Answers

$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.

like image 175
Will Vousden Avatar answered Sep 20 '22 17:09

Will Vousden