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

PHP Magic Methods

Magic methods are special hidden helpers PHP calls automatically at certain moments, like a door that opens on its own when you walk up. Their names start with two underscores.
Syntax
php
class ClassName {
    function __construct() { }
    function __toString() { return "text"; }
    function __get($name) { }
    function __set($name, $value) { }
}

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
// Define the class `User`
class User {
    // Define the constructor `__construct` with no parameters
    function __construct() {
        // Print "User created\n" to the output
        echo "User created\n";
    }
    // Define the magic method `__toString` with no parameters
    function __toString() {
        // Return `"User object"` from this function
        return "User object";
    }
}
// Create a new `User` instance, stored in `$user`
$user = new User();
// Print `$user` to the output
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
// Define the class `Money`
class Money {
    // Declare the private property `$amount`
    private $amount;
    // Define the constructor `__construct` taking `$amount`
    function __construct($amount) {
        $this->amount = $amount;
    }
    // Define the magic method `__toString` with no parameters
    function __toString() {
        // Return `"$" . number_format($this->amount, 2)` from this function
        return "$" . number_format($this->amount, 2);
    }
}
// Print `new Money(19.5)` to the output
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
// Define the class `Config`
class Config {
    // Declare the private property `$data`, set to `[]`
    private $data = [];
    // Define the magic method `__set` taking `$name`, `$value`
    function __set($name, $value) {
        $this->data[$name] = $value;
    }
    // Define the magic method `__get` taking `$name`
    function __get($name) {
        // Return `$this->data[$name] ?? null` from this function
        return $this->data[$name] ?? null;
    }
}
// Create a new `Config` instance, stored in `$config`
$config = new Config();
$config->theme = "dark";
// Print `$config->theme` to the output
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
// Define the class `Model`
class Model {
    // Define the magic method `__call` taking `$name`, `$args`
    function __call($name, $args) {
        // Print "Called method: $name\n" to the output
        echo "Called method: $name\n";
    }
}
// Create a new `Model` instance, stored in `$model`
$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
// Define the class `Product`
class Product {
    // Declare the private property `$data`, set to `[]`
    private $data = [];
    // Define the magic method `__get` taking `$name`
    function __get($name) {
        // Print "Reading '$name' via magic method\n" to the output
        echo "Reading '$name' via magic method\n";
        // Return `$this->data[$name] ?? null` from this function
        return $this->data[$name] ?? null;
    }
}
// Create a new `Product` instance, stored in `$p`
$p = new Product();
// Print `$p->price` to the output
echo $p->price;
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting that __get and __set only run for inaccessible or missing properties.
  2. Returning something other than a string from __toString.
  3. Calling a magic method directly instead of relying on PHP to call it.

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.