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)
- <?php
- class CallMagicMethod
- {
- public function __call($nameCall, $arguments)
- {
- echo "Calling object method '$nameCall' ". implode(', ', $arguments). "<br/>";
- }
- public static function __callStatic($nameCallStatic, $arguments)
- {
- echo "Calling static method '$nameCallStatic' ". implode(', ', $arguments). "<br/>";
- }
- }
- $obj = new CallMagicMethod;
- $obj->HelloTest('object context');
- CallMagicMethod::HelloTest(' static context'
- ?>
__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)
- <?php
- class GetSet
- {
- private $arr = array();
- public $declared = 1;
- private $hidden = 2;
- public function __set($name, $value)
- {
- echo "__set method = '$name' to '$value'<br/>";
- $this->arr[$name] = $value;
- }
- public function __get($name)
- {
- echo "__get method ='$name'";
- if (array_key_exists($name, $this->arr)) {
- return $this->arr[$name];
- }
- }
- public function __isset($name)
- {
- echo "__isset method = '$name' ";
- return isset($this->arr[$name]);
- }
- public function __unset($name)
- {
- echo "__unset method = '$name'";
- unset($this->arr[$name]);
- }
- }
- $obj = new GetSet;
- $obj->Value = 1001;
- echo $obj->Value . "<br/>";
- var_dump(isset($obj->Value));
- unset($obj->Value);
- echo "<br/>";
- var_dump(isset($obj->Value));
- ?>
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 )
- <?php
- class ConnectToDatabase
- {
- protected $link;
- private $dsn, $uid, $pwd;
- public function __construct($dsn, $uid, $pwd)
- {
- $this->dsn = $dsn;
- $this->username = $uid;
- $this->password = $pwd;
- $this->connect();
- }
- private function connect()
- {
- $this->link = new PDO($this->dsn, $this->username, $this->password);
- }
- public function __sleep()
- {
- return array('dsn', 'username', 'password');
- }
- public function __wakeup()
- {
- $this->connect();
- }
- }
- ?>
__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 )
- <?php
- class A
- {
- public $val;
- public function __construct($val)
- {
- $this->val = $val;
- }
- public function __toString()
- {
- return $this->val;
- }
- }
- $obj = new A('Hello');
- echo $obj;
- ?>
__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 ( [ $ ... } )
-
-
- <?php
- class A
- {
- public function __invoke($x)
- {
- var_dump($x);
- }
- }
- $obj = new A;
- $obj(5);
- ?>
__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 )
- <?php
- class A
- {
- public $var1;
- public $var2;
- public static function __set_state($an_array)
- {
- $obj = new A;
- $obj->var1 = $an_array['var1'];
- $obj->var2 = $an_array['var2'];
- return $obj;
- }
- }
- $a = new A;
- $a->var1 = 5;
- $a->var2 = 'rajeev';
- eval('$b = ' . var_export($a, true) . ';');
- var_dump($b);
- ?>
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.