Magic methods in PHP are special predefined methods that begin with double underscores __. PHP automatically calls these methods in response to specific object-related actions.
Magic methods must be declared as public and follow strict naming conventions. They are not called directly; PHP invokes them internally when required.
// Demonstration of common PHP magic methods
// Triggered when setting inaccessible properties
public function __set($name, $value) {
echo "Setting '$name' to '$value'
";
$this->data[$name] = $value;
}
// Triggered when accessing inaccessible properties
public function __get($name) {
return $this->data[$name] ?? null;
}
// Triggered when object is used like a function
public function __invoke($msg) {
echo "Object invoked with message: $msg
";
}
// Triggered when object is treated as a string
public function __toString() {
return "Demo object as string";
}
}
$obj = new Demo();
$obj->name = "Alice";
echo $obj->name;
echo "
".$obj;
$obj("Hello!");
?>
__set() stores dynamic data.__get() retrieves stored values.__toString() enables echoing the object.__invoke() allows function-like calls.__construct() – Runs when object is created.__destruct() – Runs when object is destroyed.__get() – Handles inaccessible properties.__set() – Assigns inaccessible properties.__call() – Handles inaccessible methods.__callStatic() – Handles inaccessible static methods.__isset() – Triggered by isset().__unset() – Triggered by unset().__sleep() – Before serialization.__wakeup() – After unserialization.__clone() – When cloning objects.__invoke() – When object is called as function.__toString().__get() and __set().__call() for undefined methods.__invoke().__sleep() and __wakeup().__toString() method.