Jump to content

Reference Question


arianhojat

Recommended Posts

had question about References in the php manual....

 

"When assigning an already created instance of an object to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A new instance of an already created object can be made by cloning it."

class SimpleClass
{
    // member declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
$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); //prints out

 

 

Now the manual seems to suggest u have to manually clone an object if you want to copy it to another variable by using clone() in php5, and just assigning a variable to an object, that it will make it a reference and not a copy.

 

Is that really true? cause it seems to suggest u have to manually have to add &= for reference to work (unless use 'new' operator which automatically adds a &=). $assigned seems to have cloned its own copy of $instance without using clone().

Link to comment
https://forums.phpfreaks.com/topic/38356-reference-question/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.