Understanding PHP Magic Methods: __toString, __invoke, __set_state, __clone, __autoload, and __debugInfo
This article explains the purpose, usage, constraints, and example code for several PHP magic methods—including __toString, __invoke, __set_state, __clone, __autoload, and __debugInfo—showing their effects, common pitfalls, and how they improve object handling and debugging in modern PHP applications.
This guide introduces the most commonly used PHP magic methods, describing their purpose, important notes, and providing runnable code examples.
1. __toString()
When an object is treated as a string (e.g., echo $obj; ), PHP calls __toString() . The method must return a string; otherwise a E_RECOVERABLE_ERROR is triggered. Throwing exceptions inside this method also causes a fatal error.
<?php
class Person {
public $sex;
public $name;
public $age;
public function __construct($name="", $age=25, $sex='男') {
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
public function __toString() {
return 'go go go';
}
}
$person = new Person('小明'); // initial assignment
echo $person;Output: go go go
If the method is omitted, attempting to echo the object results in a fatal error like Catchable fatal error: Object of class Person could not be converted to string .
2. __invoke()
Available from PHP 5.3.0, __invoke() is called when an object is used as a function.
<?php
class Person {
public $sex;
public $name;
public $age;
public function __construct($name="", $age=25, $sex='男') {
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
public function __invoke() {
echo '这可是一个对象哦';
}
}
$person = new Person('小明');
$person();Output: 这可是一个对象哦
Calling the object without defining __invoke() produces a fatal error: Fatal error: Function name must be a string .
3. __set_state()
From PHP 5.1.0, __set_state() is invoked by var_export() to recreate an object from an exported array.
Without the method:
<?php
class Person {
public $sex;
public $name;
public $age;
public function __construct($name="", $age=25, $sex='男') {
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
}
$person = new Person('小明');
var_export($person);Result: Person::__set_state(array('sex' => '男', 'name' => '小明', 'age' => 25, ))
With a custom static method:
<?php
class Person {
public $sex;
public $name;
public $age;
public function __construct($name="", $age=25, $sex='男') {
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
public static function __set_state($an_array) {
$a = new Person();
$a->name = $an_array['name'];
return $a;
}
}
$person = new Person('小明');
$person->name = '小红';
var_export($person);Result: Person::__set_state(array('sex' => '男', 'name' => '小红', 'age' => 25, ))
4. __clone()
The __clone() method is automatically called after an object is duplicated with the clone keyword. PHP performs a shallow copy of properties; references remain references.
<?php
class Person {
public $sex;
public $name;
public $age;
public function __construct($name="", $age=25, $sex='男') {
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
public function __clone() {
echo __METHOD__ . "你正在克隆对象
";
}
}
$person = new Person('小明');
$person2 = clone $person;
var_dump('persion1:');
var_dump($person);
echo "
";
var_dump('persion2:');
var_dump($person2);The output shows the custom message from __clone() followed by the dumped objects, confirming that cloning succeeded.
5. __autoload()
Before PHP 5.3, developers manually included class files, leading to unnecessary file loading. Defining __autoload() lets PHP automatically load a missing class file when it is first referenced.
<?php
function __autoload($className) {
$filePath = "project/class/{$className}.php";
if (is_readable($filePath)) {
require($filePath);
}
}
if (conditionA) {
$a = new A();
$b = new B();
$c = new C();
} else if (conditionB) {
$a = new A();
$b = new B();
}Only the classes actually needed are loaded, reducing compilation overhead. Modern PHP prefers spl_autoload_register() , but the principle remains the same.
6. __debugInfo()
Available from PHP 5.6.0, __debugInfo() customizes the information shown by var_dump() for an object.
<?php
class C {
private $prop;
public function __construct($val) {
$this->prop = $val;
}
public function __debugInfo() {
return [
'propSquared' => $this->prop ** 2,
];
}
}
var_dump(new C(42));Result: object(C)#1 (1) { ["propSquared"]=> int(1764) }
Note: the exponent operator ** requires PHP 5.6 or later.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
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.