Object References In PHP – Info PHP

Introduction

This article explains Object 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 variable does not contain the item itself as a value any longer. It solely contains an associated symbol that permits accesses to seek out the specific once an associated 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 . 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 and reference examples.

Example

class test

{

    public $value4emo = 22;

$value1 = new test;

$value2 = $value1; 

//same identifier $value2 and $value2

$value2->demo = 44;

echo $value1->demo.
;

$value3 = new test;

$value4 = &$value3; 

//references are $value3 and $value4    

$value4->demo = 44;

echo $value3->demo.
;

$t = new test;

function demo($obj)

{

    $obj->demo = 44;

}

demo($t);

echo $t->demo.
;

?>

  
Output

 

Example 

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

$obj2->a($obj1);

echo $obj1->a .
;

$obj2->bar($obj1);

echo $obj1->a .
;

?>

 

Output

object References

Example

$value1 = “php is good”.
;

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

$value2=” this is like a C”.
;
//override the value1

echo $value1;

echo $value1=” that’s good”.
;

unset($value2); //destroy a value2

$value2=“java is good”.
;
//create a new value

echo $value1;

$value3=“object”;

$value4=“references”;

echo $value3.
;

echo $value4.
;

exchangevalue($value3, $value4);

echo $value3.
;

echo $value4.
;

exchangeref($value3, $value4);

echo $value3.
;

echo $value4.
;

function exchangevalue($a,$b){

$extra=$a;

$a=$b;

$b=$extra;

}

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

 $extra=$a;

 $a=$b;

$b=$extra;

}

?>
 

Output

object References

Article Prepared by Ollala Corp

You might also like More from author

Leave A Reply

Your email address will not be published.