Object References In PHP

Introduction

This article explains Object References in PHP. Object references were introduced in PHP5 and one of the important featrures of PHP5 OOP that's typically mentioned is that "objects are transferred by reference by default". This is often not fully true. A PHP reference is associated with an alias that permits 2 completely different variables to write to an identical value. As of PHP5, an associated object variable does not contain the item itself as a value any longer. It solely contains an associated object symbol that permits object accesses to seek out the specific object once an associated object is shipped by argument, or assigned to a different variable, the various variables aren't aliases they hold a duplicate of the identifier, that points to the identical object. In PHP4 you use the "&" operator to take references once a modification has been created, but PHP 5 automatically uses pass-by-reference except when explicitly specified otherwise and PHP5 uses reference handles. You can see below somee object and reference examples.

Example

<?php

class test

{

    public $value4emo = 22;

$value1 = new test;

$value2 = $value1; 

//same identifier $value2 and $value2

$value2->demo = 44;

echo $value1->demo."<br>";

$value3 = new test;

$value4 = &$value3; 

//references are $value3 and $value4    

$value4->demo = 44;

echo $value3->demo."<br>";

$t = new test;

function demo($obj)

{

    $obj->demo = 44;

}

demo($t);

echo $t->demo."<br>";

?>

  
Output


object References 


Example 

<?php

class test {

    public $a = 22;

class demo {

    public function a (test $b)

    {

        $b->a= 44;

    }

    public function bar(test $b)

    {

        $b = new test;

    }

}

$obj1 = new test;

$obj2 = new demo;

echo $obj1->a . "<br>";

$obj2->a($obj1);

echo $obj1->a . "<br>";

$obj2->bar($obj1);

echo $obj1->a . "<br>";

?>

 

Output

object References

Example

<?php

$value1 = "php is good"."<br>";

$value2 = &$value1; //here references of value1

$value2=" this is like a C"."<br>";//override the value1

echo $value1;

echo $value1=" that's good"."<br>";

unset($value2); //destroy a value2

$value2="java is good"."<br>";//create a new value

echo $value1;

$value3="object";

$value4="references";

echo $value3."<br>";

echo $value4."<br>";

exchangevalue($value3, $value4);

echo $value3."<br>";

echo $value4."<br>";

exchangeref($value3, $value4);

echo $value3."<br>";

echo $value4."<br>";

function exchangevalue($a,$b){

$extra=$a;

$a=$b;

$b=$extra;

}

function exchangeref(&$a, &$b){

 $extra=$a;

 $a=$b;

$b=$extra;

}

?>
 

Output


object References

Up Next
    Ebook Download
    View all
    Learn
    View all