PHP has lot of magic stored in it. Magic methods in PHP is one way to witness it. These methods are executed automatically on certain event or situation. The function names __construct, __destruct, __get, __set etc are known as magic methods in PHP classes. That means these function names are reserved and you cannot have these function names in your PHP classes when writing you favorite PHP code. According to a disclaimer on PHP’s official site, it is mentioned that all functions starting with __ (double underscore) is reserved in PHP.
So what does these magical methods do and how can you benefit from these. A common example is the magic method __construct which gets called automatically when an object of a class is created and similarly __destruct is executed when as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.
Example of magic method explained using __get and __set :
<?php class foo { private $private_var = 'my private variable'; function __construct() { echo 'Called __contruct();<br/>'; } function __get($name) { echo "Called __get(); with argument $name"; } function __set($name,$value) { echo "Called __set(); with argument $name and value = $value"; } } $obj=new foo();//output ->> Called __contruct(); $obj->private_var;//output ->> Called __get(); with argument private_var $obj->pop; //output ->> Called __get(); with argument pop $obj->pop='foo'; //output ->> Called __set(); with argument pop and value = foo unset ($obj); ?> |
In the above example I have shown practical example of using __get and _set magic methods of PHP. The __get function or method is called when an inaccessible property is of a class is accessed. In normal case you won’t see any errors showing up but a call to the variable has been made, which has not fetched any result. So to avoid such cases or handle such failed calls we use __get function. It is only used to handle properties which are not present instead one can handle request to the variables which are not accessible in the calling context. For example in the above code, the $private_var cannot be called directly outside the class, so in that case __get is executed to handle the request properly.
Same is with __set magic method, it gets called when user tries to set a value of the variable or property which is not present or in other terms which is not accessible.
I will be covering other magic methods pretty soon. So stay tuned.
Stay Digified !!
Sachin Khosla