Tag Archives: Methods

__clone()

Object cloning is creating a copy of an object. An object copy is created by using the clone keyword and the __clone() method cannot be called directly. In PHP, cloning an object is doing a shallow copy and not a deep copy. Meaning, the contained objects of the copied objects are not copied. If you wish for a deep copy, then you need to define the __clone() method.

When an object is cloned, PHP 5 will perform a shallow copy of all of the object’s properties. Any properties that are references to other variables will remain references.

Once the cloning is complete, if a __clone() method is defined, then the newly created object’s __clone() method will be called, to allow any necessary properties that need to be changed.

<?php
 class Customer {
 private $name;
 
 public function setName($name) {
 $this->name = $name;
 }
 
 public function getName() {
 return $this->name;
 }
 
 public function __clone() {
 $c = new Customer();
 $c->setName($this->name);
 return $c;
 }
 
 }
 
 $c1 = new Customer();
 $c1->setName("phpcode");
 
 $c2 = clone $c1;

$c2->setName("phpcodez");
 
 echo $c1->getName()."\n";
 echo $c2->getName()."\n";
?>

__invoke

PHP does not allow the passing of function pointers like other languages. Functions are not first class in PHP. Functions being first class mainly means that you can save a function to a variable, and pass it around and execute it at any time.

The __invoke method is a way that PHP can accommodate pseudo-first-class functions.

The __invoke method can be used to pass a class that can act as a closure or a continuation, or simply as a function that you can pass around.

The __invoke() method is called when a script tries to call an object as a function.

<?php
 class Invoke {
 public function __invoke($x)
 {
 var_dump($x);
 }
 }
 $obj = new Invoke;
 $obj(5);
?>