Tutorial by Examples

Whenever you attempt to retrieve a certain field from a class like so: $animal = new Animal(); $height = $animal->height; PHP invokes the magic method __get($name), with $name equal to "height" in this case. Writing to a class field like so: $animal->height = 10; Will invoke...
__construct() is the most common magic method in PHP, because it is used to set up a class when it is initialized. The opposite of the __construct() method is the __destruct() method. This method is called when there are no more references to an object that you created or when you force its deletion...
Whenever an object is treated as a string, the __toString() method is called. This method should return a string representation of the class. class User { public $first_name; public $last_name; public $age; public function __toString() { return "{$this->first_...
This magic method is called when user tries to invoke object as a function. Possible use cases may include some approaches like functional programming or some callbacks. class Invokable { /** * This method will be called if object will be executed like a function: * * $invo...
__call() and __callStatic() are called when somebody is calling nonexistent object method in object or static context. class Foo { /** * This method will be called when somebody will try to invoke a method in object * context, which does not exist, like: * * $foo->...
__sleep and __wakeup are methods that are related to the serialization process. serialize function checks if a class has a __sleep method. If so, it will be executed before any serialization. __sleep is supposed to return an array of the names of all variables of an object that should be serializ...
This method is called by var_dump() when dumping an object to get the properties that should be shown. If the method isn't defined on an object, then all public, protected and private properties will be shown. — PHP Manual class DeepThought { public function __debugInfo() { return...
__clone is invoked by use of the clone keyword. It is used to manipulate object state upon cloning, after the object has been actually cloned. class CloneableUser { public $name; public $lastName; /** * This method will be invoked by a clone operator and will prepend "C...

Page 1 of 1