← Back to PHP Course | Chapter 8: OOP | Lesson 11 of 14

PHP Magic Methods

What are Magic Methods?

Magic methods are special methods PHP calls automatically in response to certain events, always prefixed with a double underscore, like __construct(), __toString(), or __get().

Example: What are Magic Methods?

php
<?php
class User {
    function __construct() {
        echo "User created\n";
    }
    function __toString() {
        return "User object";
    }
}
$user = new User();
echo $user;
?>

The Constructor and Destructor

__toString() lets an object define what string it should turn into when used in a string context, such as echoing it directly — without it, PHP raises a fatal error trying to convert an object to a string.

Example: The Constructor and Destructor

php
<?php
class Money {
    private $amount;
    function __construct($amount) {
        $this->amount = $amount;
    }
    function __toString() {
        return "$" . number_format($this->amount, 2);
    }
}
echo new Money(19.5);
?>

Property Overloading (__get and __set)

__get() and __set() intercept access to properties that don't exist or aren't accessible normally, letting you implement custom logic (like validation or lazy loading) that runs whenever code reads or writes a virtual property.

Example: Property Overloading (__get and __set)

php
<?php
class Config {
    private $data = [];
    function __set($name, $value) {
        $this->data[$name] = $value;
    }
    function __get($name) {
        return $this->data[$name] ?? null;
    }
}
$config = new Config();
$config->theme = "dark";
echo $config->theme;
?>

Object to String (__toString)

__call() intercepts calls to methods that don't exist on the object, which is how many ORM libraries implement flexible, dynamic-looking method names without literally defining hundreds of real methods.

Example: Object to String (__toString)

php
<?php
class Model {
    function __call($name, $args) {
        echo "Called method: $name\n";
    }
}
$model = new Model();
$model->getName();
?>

Method Overloading (__call)

Because magic methods run implicitly and aren't visible in a class's normal method list, overusing them can make code harder to trace and debug — they're powerful but best reserved for cases with a genuinely good reason.

Example: Method Overloading (__call)

php
<?php
class Product {
    private $data = [];
    function __get($name) {
        echo "Reading '$name' via magic method\n";
        return $this->data[$name] ?? null;
    }
}
$p = new Product();
echo $p->price;
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.