Mastering PHP Magic Methods: 16 Essential Tricks for Developers
This guide explains the 16 most important PHP magic methods, showing when they are invoked, how to declare them, and providing clear code examples for constructors, destructors, property accessors, cloning, serialization, autoloading, and debugging to help developers write more robust object‑oriented code.
PHP is a popular server‑side language, and magic methods—functions whose names start with double underscores—play a crucial role in object‑oriented programming.
- __construct(): class constructor - __destruct(): class destructor - __call($funName, $arguments): invoked when an undefined instance method is called - __callStatic($funName, $arguments): invoked when an undefined static method is called - __get($propertyName): invoked when reading an inaccessible property - __set($property, $value): invoked when writing to an inaccessible property - __isset($property): invoked when isset() or empty() is used on an inaccessible property - __unset($property): invoked when unset() is used on an inaccessible property - __sleep(): called before serialization to specify which properties should be serialized - __wakeup(): called after deserialization for reinitialisation - __toString(): defines how an object is converted to a string - __invoke(): allows an object to be called as a function - __set_state($array): used by var_export() to recreate an object - __clone(): called when an object is cloned - __autoload($className): attempts to load an undefined class - __debugInfo(): customises var_dump() output
1. __construct()
The constructor runs automatically after an object is created. If no constructor is defined, PHP provides a default one with no parameters.
function __construct([parameter list]) {
// initialise properties
}Example:
<?php
class Person {
public $name;
public $age;
public $sex;
public function __construct($name = "", $sex = "Male", $age = 22) {
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
}
public function say() {
echo "Name: $this->name, Sex: $this->sex, Age: $this->age";
}
}
$person1 = new Person();
$person1->say(); // Name: , Sex: Male, Age: 22
$person2 = new Person("James");
$person2->say(); // Name: James, Sex: Male, Age: 22
$person3 = new Person("Jack", "Male", 25);
$person3->say(); // Name: Jack, Sex: Male, Age: 25
?>2. __destruct()
The destructor runs just before an object is destroyed, allowing cleanup such as closing files or releasing resources. It cannot accept parameters.
function __destruct() {
// cleanup code
}
?>Example:
<?php
class Person {
public $name;
public $age;
public $sex;
public function __construct($name = "", $sex = "Male", $age = 22) {
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
}
public function say() {
echo "Name: $this->name, Sex: $this->sex, Age: $this->age";
}
public function __destruct() {
echo "Well, my name is $this->name";
}
}
$person = new Person("John");
unset($person); // triggers __destruct()
?>3. __call()
When an undefined or inaccessible instance method is called, __call() receives the method name and an array of arguments.
function __call(string $function_name, array $arguments) {
// handle missing method
}
?>Example:
<?php
class Person {
public function say() { echo "Hello, world!<br>"; }
public function __call($funName, $arguments) {
echo "The function you called: $funName (parameters: ";
print_r($arguments);
echo ") does not exist!<br>
";
}
}
$person = new Person();
$person->run("teacher"); // triggers __call()
$person->eat("John", "apple"); // triggers __call()
$person->say();
?>4. __callStatic()
Similar to __call(), but for undefined static methods.
public static function __callStatic($funName, $arguments) {
// handle missing static method
}
?>Example:
<?php
class Person {
public static function __callStatic($funName, $arguments) {
echo "The static method you called: $funName (parameters: ";
print_r($arguments);
echo ") does not exist!<br>
";
}
}
Person::run("teacher");
Person::eat("John", "apple");
?>5. __get()
Allows reading of inaccessible or private properties. It can return computed values.
public function __get($propertyName) {
if ($propertyName == "age") {
return ($this->age > 30) ? $this->age - 10 : $this->age;
}
return $this->$propertyName;
}
?>Example usage prints "Name: John" and "Age: 50" when the internal age is 60.
6. __set()
Intercepts writes to inaccessible properties, allowing validation.
public function __set($property, $value) {
if ($property == "age" && ($value > 150 || $value < 0)) {
return; // reject illegal age
}
$this->$property = $value;
}
?>7. __isset()
Called when isset() or empty() is used on an inaccessible property.
public function __isset($property) {
echo "The {$property} property is private, __isset() called automatically.<br>";
return isset($this->$property);
}
?>8. __unset()
Invoked when unset() is called on an inaccessible property.
public function __unset($property) {
echo "It is called automatically when we use unset() outside the class.<br>";
unset($this->$property);
}
?>9. __sleep()
Executed before serialization; returns an array of property names to be serialized.
public function __sleep() {
echo "It is called when serialize() is invoked.<br>";
$this->name = base64_encode($this->name);
return array('name', 'age');
}
?>10. __wakeup()
Executed after unserialization for reinitialisation.
public function __wakeup() {
echo "It is called when unserialize() is invoked.<br>";
$this->name = 2; // example reinitialisation
}
?>11. __toString()
Defines how an object is converted to a string. Must return a string.
public function __toString() {
return 'go go go';
}
?>12. __invoke()
Allows an object to be called as a function.
public function __invoke() {
echo 'This is an object';
}
?>13. __set_state()
Called by var_export() to recreate an object from an array of properties.
public static function __set_state($array) {
$obj = new self();
$obj->name = $array['name'];
return $obj;
}
?>14. __clone()
Invoked when an object is cloned, allowing deep copy adjustments.
public function __clone() {
echo __METHOD__ . " you are cloning the object.<br>";
}
?>15. __autoload()
Automatically includes the file that defines an undefined class.
function __autoload($className) {
$filePath = "project/class/{$className}.php";
if (is_readable($filePath)) {
require $filePath;
}
}
?>16. __debugInfo()
Customises the output of var_dump() for an object (available from PHP 5.6).
public function __debugInfo() {
return ['propSquared' => $this->prop ** 2];
}
?>These magic methods provide powerful hooks into PHP's object model, enabling developers to control object creation, property access, method calls, serialization, and debugging.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
