Thursday, June 4, 2009

PHP5: object references, object cloning and __clone()

Let's make a simple class with a value (default=1), set and get methods

class Obj
{
private $var=1;
public function
setVal($var) { $this->var = $var; }
public function getVal() { return $this->var; }
}

Following, another class that includes the previous one (Or better, it includes a reference to the previous class, and the object will be instantiated by the constructor)

class A
{
private $obj; //reference to the previous class
private $i=1; //internal variabile
public function __construct() { $this->obj = new Obj(); }
//set the private properties and the val of the internal object !
public function
setAll($v) { $this->obj->setVal($v); $this->i =$v; }
public function
getObj() { return $this->obj->getVal(); }
public function
getI() { return $this->i; }
function
__clone()
{
$this->obj = clone $this->obj;
}
}

OBJECT ASSIGN (IT'S NOT A COPY)
Now we instantiate a class and assign its reference to other variables

$a = new A();
$aRef = &$a; // REFERENCE
$aCopy = $a; // REFERENCE as well, the same as before!!!

$a->setAll(2);

print
$aRef-> getObj(); //2
print $aRef->getI();//2
print $aCopy-> getObj();//2
print $aCopy->getI();//2

CLONING
to copy all the elements of an object to another reference/variabile, you must clone it, using "clone" keyword.
$a = new A();
$aClone = clone $a; //CLONE
$a->setAll(2); //the cloned object ($aClone) won't be modified !

print
$aClone->getI(); // "1"
print $aClone->getObj(); //"1"
thanks to the overriding __clone() method,
otherwise "2"

No comments:

Post a Comment

 

PHP and tips|PHP