Understanding PHP Magic Methods: __construct, __destruct, __call, and More
This article explains the purpose, behavior, and typical usage of PHP's magic methods—including __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state, __clone, __autoload, and __debugInfo—providing clear definitions, explanations, and code examples for each.
PHP provides a set of magic methods that are automatically invoked in specific object‑oriented scenarios, allowing developers to customize object behavior such as construction, destruction, property access, serialization, and more.
__construct()
Definition: class constructor.
Explanation: Called automatically when an object is instantiated; typically used to perform initialization tasks like assigning default values to properties.
class Person {
public $name;
public $age;
public $sex;
public function __construct($name = '', $sex = '男', $age = 28) {
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
}
// Note: If a subclass defines its own constructor, the parent constructor is not called automatically; use parent::__construct() to invoke it.
}__destruct()
Definition: class destructor.
Explanation: Executed just before an object is destroyed, allowing cleanup actions such as closing files or releasing resources.
// Explicitly destroy an object
unset($obj);
// Or let the script end and PHP will call __destruct automatically.__call()
Definition: invoked when calling an undefined or inaccessible instance method.
Explanation: Prevents fatal errors by handling calls to methods that do not exist, enabling graceful fallback logic.
public function __call($method, $args) {
// handle undefined method calls
echo "Method $method does not exist.";
}__callStatic()
Definition: similar to __call() but triggered for undefined static method calls.
public static function __callStatic($method, $args) {
echo "Static method $method does not exist.";
}__get()
Definition: provides read access to inaccessible or private properties from outside the object.
Example:
private $name;
public function __get($property) {
return $this->$property;
}
$person = new Person("小明", 60);
echo "姓名:" . $person->name; // triggers __get()__set()
Definition: allows writing to inaccessible or private properties from outside the object.
public function __set($property, $value) {
$this->$property = $value;
}__isset()
Definition: invoked when isset() or empty() is called on an inaccessible property.
public function __isset($property) {
echo "Checking if $property is set...<br>";
return isset($this->$property);
}
isset($person->name);__unset()
Definition: called when unset() is used on an inaccessible property.
public function __unset($property) {
unset($this->$property);
}__sleep()
Definition: executed automatically during serialize(); should return an array of property names to be serialized.
public function __sleep() {
$this->name = base64_encode($this->name);
return ['name', 'age'];
}
echo serialize($person);__wakeup()
Definition: called automatically during unserialize(); can be used to re‑initialize resources.
public function __wakeup() {
$this->name = base64_decode($this->name);
}__toString()
Definition: defines how an object is converted to a string, e.g., when used with echo.
Note: Must return a string; throwing an exception inside will cause a fatal error.
public function __toString() {
return "Person: {$this->name}, Age: {$this->age}";
}
echo $person; // triggers __toString()__invoke()
Definition: allows an object to be called as a function.
public function __invoke() {
echo "Calling object as a function!";
}
$person = new Person();
$person(); // triggers __invoke()__set_state()
Definition: invoked when var_export() exports a class; should return an instance of the class.
public static function __set_state($array) {
$obj = new self();
foreach ($array as $key => $value) {
$obj->$key = $value;
}
return $obj;
}__clone()
Definition: called after an object is cloned.
public function __clone() {
echo __METHOD__ . " you are cloning an object.<br>";
$this->name = 'new name';
$this->age = 18;
}
$copy = clone $person;__autoload()
Definition: automatically loads undefined classes.
function __autoload($className) {
$filePath = "project/class/{$className}.php";
if (is_readable($filePath)) {
require $filePath;
}
}
// Example usage
$a = new A();
$b = new B();__debugInfo()
Definition: provides custom debug information for var_dump().
public function __debugInfo() {
return [
'message' => "姓名:{$this->name} 年龄:{$this->age}"
];
}
$person = new Person('tongfei', 28);
var_dump($person);php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.