Introduction

In this article we will learn what the magic methods in PHP are and their functionality and uses in PHP projects. The "magic" methods are ones with special names, starting with two underscores (__), which means that the method will be triggered in response to specific PHP events. PHP reserves all function names starting with two underscores as magical methods, so do not use any function name prefixed by two underscores.

List of Magic Methods

  • __construct()
  • __destruct()
  • __call()
  • __callStatic()
  • __get()
  • __set()
  • __isset()
  • __unset()
  • __sleep()
  • __wakeup()
  • __toString()
  • __invoke()
  • __set_state() and
  • __clone()

__construct() and __destruct()

The constructor is a magic method that is called when the object is instantiated. You can find more about __construct() and __destruct() magic methods in my past article.

__call()

The __call() method is called, if defined, and when an undefined method is called on this object. This method is used for polite error handling, and this is useful in library code where other people might need to be integrating with your methods. This method is triggered when invoking inaccessible methods in an object context.

Syntax

public mixed --call ( string $name, array $argument)

__callStatic()

This method has the same functionality as the __call() method, but the only difference is this method only responds to undefined static method calls. This method was introduced by (*PHP 5.3). __callStatic is triggered when invoking inaccessible methods in a static context.

Syntax

public mixed --callStatic ( string $name, array $argument)

  1. <?php  
  2. class CallMagicMethod  
  3. {  
  4.     public function __call($nameCall$arguments)  
  5.     {  
  6.         echo "Calling object method '$nameCall' ". implode(', '$arguments). "<br/>";  
  7.     }  
  8.     public static function __callStatic($nameCallStatic$arguments)  
  9.     {  
  10.         echo "Calling static method '$nameCallStatic' ". implode(', '$arguments). "<br/>";  
  11.     }  
  12. }  
  13. $obj = new CallMagicMethod;  
  14. $obj->HelloTest('object context');  
  15. CallMagicMethod::HelloTest(' static context'  
  16. ?>  
CallCallStatic

 __get()

This method is called when code attempts to access a property that is not accessible. The __get() method accepts one argument, which is the name of the property, and returns the value and that value is treated as the property of that value. A popular use of the __get() method is to extend the access control by creating "read-only" properties.

Syntax

public void  __get( string $name)

__set()

The __set() method is used for writing data to inaccessible properties. This method accepts two arguments that are the name of the property and the value to provide for it.

Syntax

public void  __set( string $name, mixed $value)

__isset()

This method is called when we call isset() or empty() on inaccessible properties. It accepts only one argument, that is the name of the property. This method returns a Boolean value true if the value exists.

Syntax

public void  __isset( string $name)

__unset()

This method is called when we call the unset() method for the use of inaccessible properties. This method accepts one argument of the property.

Syntax

public void  __unset( string $name)

  1. <?php  
  2. class GetSet  
  3. {  
  4.     private $arr = array();  
  5.     public $declared = 1;  
  6.     private $hidden = 2;  
  7.     public function __set($name$value)  
  8.     {  
  9.         echo "__set method = '$name' to '$value'<br/>";  
  10.         $this->arr[$name] = $value;  
  11.     }  
  12.     public function __get($name)  
  13.     {  
  14.         echo "__get method ='$name'";  
  15.         if (array_key_exists($name$this->arr)) {  
  16.             return $this->arr[$name];  
  17.         }  
  18.      }  
  19.     public function __isset($name)  
  20.     {  
  21.         echo "__isset method = '$name' ";  
  22.         return isset($this->arr[$name]);  
  23.     }  
  24.     public function __unset($name)  
  25.     {  
  26.         echo "__unset method = '$name'";  
  27.         unset($this->arr[$name]);  
  28.     }  
  29.   }  
  30. $obj = new GetSet;  
  31. $obj->Value = 1001;  
  32. echo $obj->Value . "<br/>";  
  33. var_dump(isset($obj->Value));  
  34. unset($obj->Value);  
  35. echo "<br/>";  
  36. var_dump(isset($obj->Value));  
  37. ?>  
GetSetMagicFunction

 Object Serialization

Serialization is the process that converts any data into a string format. This can be done by storing our objects into a file or database. When we deserialize our stored data we get our original data as we stored as before. There is a problem with serialization, we cannot serialize everything, such as a database connection. There are some magic methods that allow us to handle this kind of problem.

__sleep()

This method is only called when we use the serialize() function. This method does not accept any arguments and clean up the object and returns an array with the names of all variables of the object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.

Syntax

public array __sleep ( void)

__wakeup()

 This method is called when the unserialize() function is called on the stored object. It also does not accept any argument and does not return anything, but it reestablishes any database connection or any resource that was lost in the serialization process.

Syntax

 void __wakeup ( void )

  1. <?php  
  2. class ConnectToDatabase  
  3. {  
  4.     protected $link;  
  5.     private $dsn$uid$pwd;  
  6.     public function __construct($dsn$uid$pwd)  
  7.     {  
  8.         $this->dsn = $dsn;  
  9.         $this->username = $uid;  
  10.         $this->password = $pwd;  
  11.         $this->connect();  
  12.     }  
  13.         private function connect()  
  14.     {  
  15.         $this->link = new PDO($this->dsn, $this->username, $this->password);  
  16.     }  
  17.         public function __sleep()  
  18.     {  
  19.         return array('dsn''username''password');  
  20.     }  
  21.         public function __wakeup()  
  22.     {  
  23.         $this->connect();  
  24.     }  
  25. }  
  26. ?>  
__toString()

This method is called when an object is returned as a string. This function doesn't take any arguments but returns a string value. Suppose we want to return a string value of "$Obj" then this object either returns a string value or rovides a fatal E_RECOVERABLE_ERROR error. We cannot throw an exception within this method, doing so will raise a fatal error.

Syntax

public string __tostring ( void )

  1. <?php  
  2. class A  
  3. {  
  4.     public $val;  
  5.     public function __construct($val)  
  6.     {  
  7.         $this->val = $val;  
  8.     }  
  9.     public function __toString()  
  10.     {  
  11.         return $this->val;  
  12.     }  
  13. }  
  14. $obj = new A('Hello');  
  15. echo $obj;  
  16. ?>  
ToString

__invoke()

This method is called when the code tries to call an object as a function. Any argument defined in this method will be used as the function arguments.

Syntax

mixed __invoke ( [ $ ... } )

  1.    
  2.   
  3. <?php  
  4. class A  
  5. {  
  6.     public function __invoke($x)  
  7.     {  
  8.         var_dump($x);  
  9.     }  
  10. }  
  11. $obj = new A;  
  12. $obj(5);  
  13. ?>  

 InvokeOutPut

__set_state()

The static __set_state() method is used when we call the var_expory() function. The var_export() function is used to convert a variable to PHP code. This method accepts an associative array containing the property values of the object.

Syntax

static object __set_state( array $properties )
  1. <?php  
  2. class A  
  3. {  
  4.     public $var1;  
  5.     public $var2;  
  6.     public static function __set_state($an_array)   
  7.     {  
  8.         $obj = new A;  
  9.         $obj->var1 = $an_array['var1'];  
  10.         $obj->var2 = $an_array['var2'];  
  11.         return $obj;  
  12.     }  
  13. }  
  14. $a = new A;  
  15. $a->var1 = 5;  
  16. $a->var2 = 'rajeev';  
  17. eval('$b = ' . var_export($a, true) . ';');  
  18. var_dump($b);  
  19. ?>  
SetState

 Cloning Objects

Objects, default, are passed around by reference. So assinging other variables to an object will not actually copy the object, it will simply create a new reference to the same object. In order to truly copy an object, we must use the clone keyword.
This is a "pass by reference" policy. Even if we clone an object, any child objects will be not cloned.

__clone()

This method can be used to solve this kind of problem. It is called on the copy of a cloned object after the cloning takes place. This is where we can clone any child objects.

Summary

In this article we have learned all the magic methods in PHP. These magic methods are also part of Object Oriented Programming.

Next Recommended Readings