0
0
PHPprogramming~5 mins

Why magic methods exist in PHP

Choose your learning style9 modes available
Introduction

Magic methods let PHP objects do special things automatically. They help make code easier and cleaner by handling common tasks behind the scenes.

When you want to run code automatically when an object is created or destroyed.
When you want to control what happens if someone tries to get or set a property that does not exist.
When you want to customize how an object converts to a string.
When you want to handle method calls that are not defined in the class.
Syntax
PHP
<?php
class MyClass {
    public function __construct() {
        // Code runs when object is created
    }

    public function __destruct() {
        // Code runs when object is destroyed
    }

    public function __get($name) {
        // Code runs when getting a property that does not exist
    }

    public function __set($name, $value) {
        // Code runs when setting a property that does not exist
    }

    public function __toString() {
        // Code runs when object is used as a string
        return "";
    }

    public function __call($name, $arguments) {
        // Code runs when calling a method that does not exist
    }
}
?>

Magic methods always start with two underscores (__).

They are called automatically by PHP in special situations.

Examples
This example uses __set and __get to store and retrieve properties dynamically.
PHP
<?php
class Person {
    private $data = [];

    public function __set($name, $value) {
        $this->data[$name] = $value;
    }

    public function __get($name) {
        return $this->data[$name] ?? 'Not set';
    }
}

$person = new Person();
$person->age = 30;
echo $person->age;
?>
This example shows __construct and __destruct running automatically when the object is created and destroyed.
PHP
<?php
class Logger {
    public function __construct() {
        echo "Logger started\n";
    }

    public function __destruct() {
        echo "Logger stopped\n";
    }
}

$log = new Logger();
?>
This example shows how __toString lets an object be printed as a string.
PHP
<?php
class Message {
    public function __toString() {
        return "Hello from Message!";
    }
}

$msg = new Message();
echo $msg;
?>
Sample Program

This program shows magic methods working together: constructor, setter, getter, toString, and destructor. It prints messages automatically when properties are set or accessed, and when the object is created or destroyed.

PHP
<?php
class MagicDemo {
    private $properties = [];

    public function __construct() {
        echo "Object created\n";
    }

    public function __set($name, $value) {
        echo "Setting '$name' to '$value'\n";
        $this->properties[$name] = $value;
    }

    public function __get($name) {
        echo "Getting '$name'\n";
        return $this->properties[$name] ?? "Property '$name' not found";
    }

    public function __toString() {
        return "MagicDemo object with properties: " . implode(", ", array_keys($this->properties));
    }

    public function __destruct() {
        echo "Object destroyed\n";
    }
}

$demo = new MagicDemo();
$demo->color = 'blue';
echo $demo->color . "\n";
echo $demo . "\n";
?>
OutputSuccess
Important Notes

Magic methods help you write less code for common tasks.

They make your objects behave more like built-in types.

Use them carefully to keep code clear and easy to understand.

Summary

Magic methods run automatically in special situations.

They help manage object creation, property access, method calls, and string conversion.

Using magic methods can make your code cleaner and more flexible.