PHP functions that start with a double underscore – a “__” – are called magic functions (and/or methods) in PHP. They are functions that are always defined inside classes, and are not stand-alone (outside of classes) functions. The magic functions available in PHP are: __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone(), and __autoload(). We are not going to cover each one of these in this article, but I will show you a few use cases.
Why are they called magic functions?
PHP does not provide the definitions of the magic functions – the programmer must actually write the code that defines what the magic function will do. But, magic functions will never directly be called by the programmer – actually, PHP will call the function ‘behind the scenes’. This is why they are called ‘magic’ functions – because they are never directly called, and they allow the programmer to do some pretty powerful things. Confused? An example will help make this clear.
Example of using the __construct() magic function in PHP
Example of using the __construct() magic function in PHP
The most commonly used magic function is __construct(). This is because as of PHP version 5, the __construct method is basically the constructor for your class. If PHP 5 can not find the __construct() function for a given class, then it will search for a function with the same name as the class name – this is the old way of writing constructors in PHP, where you would just define a function with the same name as the class.
class Animal { public $height; // height of animal public $weight; // weight of animal public function __construct($height, $weight) { $this->height = $height; //set the height instance variable $this->weight = $weight; //set the weight instance variable } }
In the code above, we have a simple __construct function defined that just sets the height and weight of an animal object. So let’s say that we create an object of the Animal class with this code
Animal obj = new Animal(5, 150);
What happens when we run the code above? Well, a call to the __construct() function is made because that is the constructor in PHP 5. And the obj object will be an object of the Animal class with a height of 5 and a weight of 150. So, the __construct function is called behind the scenes.
No comments:
Post a Comment