Tag Archives: Magic

__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);
?>

Magic Constants

Definition

• PHP Provides a set of predefined constants defined by the php core (EX: E_ERROR; TRUE)

• Several of these can change, depending upon where they are used.

Therefore, not true constants (EX: __DIR__; __NAMESPACE__).

• __DIR__: returns the current working directory
• __FILE__: returns the current working directory and file name
• __FUNCTION__: returns the current function name
• __CLASS__: returns the current class and namespace if defined
• __LINE__: returns the current line number at the point of use
• __METHOD__: returns the current method name
• __TRAIT__: returns the trait name including namespace if defined.
• __NAMESPACE__: returns the current namespace

Example

ClassName::class: returns the fully qualified class name

<?php
 namespace NS {
 class ClassName {}
 echo ClassName::class;
 }
?>

It outputs NS\ClassNam