Web Analytics

PHP Magic Methods

Advanced~30 min read

Magic methods are special methods that PHP calls automatically in specific situations. They start with __ (double underscore) and enable powerful dynamic behavior!

Output
Click Run to execute your code

Common Magic Methods

Method Called When
__get($name) Accessing inaccessible property
__set($name, $value) Setting inaccessible property
__toString() Object used as string
__call($name, $args) Calling inaccessible method
__isset($name) isset() on inaccessible property

__get and __set

<?php
class Magic {
    private $data = [];
    
    public function __get($name) {
        return $this->data[$name] ?? null;
    }
    
    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
}

$obj = new Magic();
$obj->name = "John";  // Calls __set
echo $obj->name;      // Calls __get
?>

__toString

<?php
class User {
    public function __toString() {
        return "User object";
    }
}

$user = new User();
echo $user;  // "User object"
?>

Summary

  • Magic methods: Start with __
  • Automatic: PHP calls them
  • __get/__set: Dynamic properties
  • __toString: String conversion
  • __call: Dynamic methods

What's Next?

Congratulations! You've completed Module 7 (OOP). Next, dive into Superglobals & Forms - handling user input!