Backend Development 16 min read

Understanding PHP Magic Methods: Constructors, Destructors, Call, CallStatic, Get, Set, Isset, Unset, Sleep and Wakeup

This article explains the purpose, declaration syntax, usage rules, and practical examples of PHP's magic methods—including __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, and __wakeup—providing clear code snippets and output demonstrations for each.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Understanding PHP Magic Methods: Constructors, Destructors, Call, CallStatic, Get, Set, Isset, Unset, Sleep and Wakeup

PHP magic methods are special functions whose names start with double underscores and are automatically invoked by the engine in specific situations. The article introduces each method, explains its role, shows the correct declaration format, and provides runnable examples.

1. __construct() – the class constructor, called when an object is instantiated. It is used for initializing properties. Example:

name = $name;
        $this->sex  = $sex;
        $this->age  = $age;
    }
    public function say() {
        echo "我叫:" . $this->name . ",性别:" . $this->sex . ",年龄:" . $this->age;
    }
}
$Person1 = new Person();
echo $Person1->say(); // 输出: 我叫:,性别:男,年龄:22
$Person2 = new Person("小明");
echo $Person2->say(); // 输出: 我叫:小明,性别:男,年龄:22
$Person3 = new Person("李四", "男", 25);
echo $Person3->say(); // 输出: 我叫:李四,性别:男,年龄:25
?>

2. __destruct() – the destructor, executed just before an object is destroyed, useful for cleanup tasks such as closing files. Example:

name = $name; }
    public function __destruct() { echo "我觉得我还可以再抢救一下,我的名字叫" . $this->name; }
}
$Person = new Person("小明");
unset($Person); // 触发 __destruct()
?>

Output: 我觉得我还可以再抢救一下,我的名字叫小明

3. __call($function_name, $arguments) – invoked when an inaccessible or non‑existent instance method is called. It prevents fatal errors and allows custom handling. Example:

"; }
    public function __call($funName, $arguments) {
        echo "你所调用的函数:" . $funName . "(参数:";
        print_r($arguments);
        echo ")不存在!
\n";
    }
}
$Person = new Person();
$Person->run("teacher");
$Person->eat("小明", "苹果");
$Person->say();
?>

Output shows the missing‑method messages followed by "Hello, world!".

4. __callStatic($function_name, $arguments) – similar to __call but for static method calls. Example:

\n";
    }
    public function say() { echo "Hello, world!
"; }
}
Person::run("teacher");
Person::eat("小明", "苹果");
$person = new Person();
$person->say();
?>

Output displays static‑method missing messages and then the normal greeting.

5. __get($property) – called when reading an inaccessible property, often used to expose private data safely. Example:

name = $name; $this->age = $age; }
    public function __get($propertyName) {
        if ($propertyName == "age" && $this->age > 30) {
            return $this->age - 10;
        }
        return $this->$propertyName;
    }
}
$Person = new Person("小明", 60);
echo "姓名:" . $Person->name . "
"; // 通过 __get()
echo "年龄:" . $Person->age . "
";   // 结果为 50
?>

6. __set($property, $value) – invoked when writing to an inaccessible property, allowing validation before assignment. Example:

name = $name; $this->age = $age; }
    public function __set($property, $value) {
        if ($property == "age" && ($value < 0 || $value > 150)) return; // reject illegal ages
        $this->$property = $value;
    }
    public function say() { echo "我叫".$this->name.",今年".$this->age."岁了"; }
}
$Person = new Person("小明", 25);
$Person->name = "小红"; // triggers __set()
$Person->age = 16;      // triggers __set()
$Person->age = 160;    // ignored
$Person->say(); // 输出: 我叫小红,今年16岁了
?>

7. __isset($property) – called when isset() or empty() is used on an inaccessible property, enabling custom existence checks. Example:

name = $name; $this->age = $age; $this->sex = $sex; }
    public function __isset($content) {
        echo "当在类外部使用isset()函数测定私有成员{$content}时自动调用
";
        echo isset($this->$content);
    }
}
$person = new Person("小明", 25);
var_dump(isset($person->sex));   // true (public)
$person->__isset('name');        // triggers __isset()
$person->__isset('age');         // triggers __isset()
?>

8. __unset($property) – invoked when unset() is called on an inaccessible property, allowing custom cleanup. Example:

name = $name; $this->age = $age; $this->sex = $sex; }
    public function __unset($content) {
        echo "当在类外部使用unset()函数来删除私有成员时自动调用的
";
        echo isset($this->$content);
    }
}
$person = new Person("小明", 25);
unset($person->sex);   // public, normal unset
$person->__unset('name'); // triggers __unset()
$person->__unset('age');  // triggers __unset()
?>

9. __sleep() – executed before serialization; it can clean up the object and return an array of property names that should be serialized. Example:

name = $name; $this->age = $age; $this->sex = $sex; }
    public function __sleep() {
        echo "当在类外部使用serialize()时会调用这里的__sleep()方法
";
        $this->name = base64_encode($this->name);
        return ['name', 'age'];
    }
}
$person = new Person('小明');
echo serialize($person);
?>

Output shows the custom message, the base64‑encoded name, and a serialized string containing only the selected properties.

10. __wakeup() – called after unserialization to re‑initialize resources (e.g., database connections). Example:

name = $name; $this->age = $age; $this->sex = $sex; }
    public function __sleep() { echo "当在类外部使用serialize()时会调用这里的__sleep()方法
"; $this->name = base64_encode($this->name); return ['name','age']; }
    public function __wakeup() { echo "当在类外部使用unserialize()时会调用这里的__wakeup()方法
"; $this->name = 2; $this->sex = '男'; }
}
$person = new Person('小明');
$ser = serialize($person);
var_dump(unserialize($ser));
?>

The script demonstrates that __sleep() runs during serialization, while __wakeup() runs during unserialization, restoring object state.

Overall, the article provides a comprehensive reference for all major PHP magic methods, illustrating their signatures, constraints, and typical use‑cases with complete code samples.

BackendProgrammingPHPoopMagic Methods
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.