What are magic methods in PHP?
Magic methods are special methods in PHP classes. Their names start with a double underscore (__). PHP calls them automatically in some situations, you do not call them yourself.
| Method | When PHP calls it |
|---|---|
| __construct() | When an object is created |
| __destruct() | When an object is destroyed |
| __get($name) | When reading a property that is not accessible or does not exist |
| __set($name, $value) | When writing to a property that is not accessible or does not exist |
| __call($name, $args) | When calling a method that does not exist |
| __toString() | When an object is used as a string, for example with echo |
| __invoke() | When an object is called like a function |
<?php
class User {
private $data = ["name" => "Robin"];
public function __get($key) {
return $this->data[$key] ?? "Not found";
}
public function __toString() {
return "User: " . $this->data["name"];
}
}
$u = new User();
echo $u->name . "<br>";
echo $u->city . "<br>";
echo $u;
?>
Output:
Tutorials Class - Output Window
Robin
Not found
User: Robin
Do not create your own methods with a double underscore name, because PHP keeps these names for itself.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |