OOP and References in PHP
Object Oriented Programming in PHP – Part 7
Forward: In this part of the series, we look at object references.
By: Chrysanthus Date Published: 9 Aug 2012
Introduction
Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.
Assigning an Object Variable to another Variable
When you assign an object variable to a new variable, as object $a is assigned to $b below, both variables still refer to the same region (object) in memory; no copy of the region content is made to another region. Read and try the following code:
<?php
class A
{
public $var = 1;
}
$a = new A;
$b = $a;
$b->var= 2;
echo $a->var."<br />";
echo $b->var."<br />";
?>
When you assign an object reference to a new variable, as &$c is assigned to $d below, the results are the same as copying an object variable to another; no memory region content is copied to another memory region. Read and try the following code:
<?php
class A
{
public $var = 1;
}
$c = new A;
$d = &$c;
$d->var= 2;
echo $c->var."<br />";
echo $d->var."<br />";
?>
Passing an Object as Ordinary Argument to a Function
When you pass an object as argument to a function, both the parameter object and the object outside the function, refer to the same region (object) in memory. Read and try the following code:
<?php
class A
{
public $var = 1;
}
$e = new A;
echo $e->var . "<br />";
function fn($obj)
{
$obj->var = 2;
echo $obj->var . "<br />";
}
fn($e);
echo $e->var . "<br />";
?>
When you pass an object by reference to a function, the results are the same as passing the object ordinarily. Read and try the following code:
<?php
class A
{
public $var = 1;
}
$e = new A;
echo $e->var . "<br />";
function fn(&$obj)
{
$obj->var = 2;
echo $obj->var . "<br />";
}
fn($e);
echo $e->var . "<br />";
?>
Let us stop here for this part of the series and continue in the next part.
Chrys
Related Links
Major in Website DesignWeb Development Course
HTML Course
CSS Course
ECMAScript Course
PHP Course