Home Tutorial Php Phpoop PHP Object Reference

 
 

PHP Object Reference
Posted on: February 27, 2010 at 12:00 AM
In this current tutorial we will study about what is object and what is reference? how to create object in PHP, how to give reference to another object etc. In PHP a reference is an alias and an object variable does not contain the object rather it contains the identifier and it allows to access the actual object.

PHP Object and References:

It is a very common misconception about object that the terms object and reference is interchangeable. Now we must know what is actually an object and what is a reference.

Whenever an object is instantiated it occupies some memory, that memory chunk is called an object and the name or identifier which refers to that memory chunk is called a reference. But in general we call the first reference of that memory chunk as object and the objects which are used to refer the first object as reference. 

Similarly in PHP a reference is an alias and an object variable does not contain the object rather it contains the identifier and it allows to access the actual object.   

Example:

<?php

class A{

public $var=2;

}

$a=new A();

$b=$a;

$b->var=4;

echo "\$a=".$a->var."<br/>";

$c=new A();

$d=&$c;

$d->var=43;

echo "\$c=".$c->var."<br/>";

function display($obj){

$obj->var=34;

}

$e=new A();

display($e);

echo "\$c=".$e->var."<br/>";

?>

Output:

$a=4
$c=43
$c=34

 

Related Tags for PHP Object Reference:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.