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.

MethodWhen 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
PHP OOP Introduction
PHP Class
PHP Objects
Exercises & Assignments
No Content Found.
Interview Questions & Answers
How to create a class and object in PHP?
What is the difference between public, private and protected in PHP?
Is multiple inheritance supported in PHP?
What is the meaning of final class and final method in PHP?
What is the difference between abstract class and interface in PHP?
What are traits in PHP?
What is a constructor in PHP?