← Back to Chapters

PHP OOP Magic Methods

✨ PHP OOP Magic Methods

? Quick Overview

Magic methods in PHP are special predefined methods that begin with double underscores __. PHP automatically calls these methods in response to specific object-related actions.

? Key Concepts

  • Magic methods respond to object lifecycle events.
  • They allow interception of property access and method calls.
  • Used heavily in frameworks, ORMs, and dynamic systems.

? Syntax & Theory

Magic methods must be declared as public and follow strict naming conventions. They are not called directly; PHP invokes them internally when required.

? Code Example

? View Code Example
// Demonstration of common PHP magic methods
// Triggered when setting inaccessible properties
public function __set($name, $value) {
echo "Setting '$name' to '$value'
";
$this->data[$name] = $value;
}

// Triggered when accessing inaccessible properties
public function __get($name) {
return $this->data[$name] ?? null;
}

// Triggered when object is used like a function
public function __invoke($msg) {
echo "Object invoked with message: $msg
";
}

// Triggered when object is treated as a string
public function __toString() {
return "Demo object as string";
}
}

$obj = new Demo();
$obj->name = "Alice";
echo $obj->name;
echo "
".$obj;
$obj("Hello!");
?>

? Live Output / Explanation

Output Behavior

  • __set() stores dynamic data.
  • __get() retrieves stored values.
  • __toString() enables echoing the object.
  • __invoke() allows function-like calls.

? Common Magic Methods

  • __construct() – Runs when object is created.
  • __destruct() – Runs when object is destroyed.
  • __get() – Handles inaccessible properties.
  • __set() – Assigns inaccessible properties.
  • __call() – Handles inaccessible methods.
  • __callStatic() – Handles inaccessible static methods.
  • __isset() – Triggered by isset().
  • __unset() – Triggered by unset().
  • __sleep() – Before serialization.
  • __wakeup() – After unserialization.
  • __clone() – When cloning objects.
  • __invoke() – When object is called as function.

? Use Cases

  • Dynamic property handling
  • Lazy loading data
  • Proxy and decorator patterns
  • Framework-level abstractions

✅ Tips & Best Practices

  • Use magic methods sparingly and intentionally.
  • Document behavior clearly for maintainability.
  • Always return a string from __toString().
  • Prefer explicit methods when clarity matters.

? Try It Yourself

  • Create a class using __get() and __set().
  • Implement __call() for undefined methods.
  • Experiment with __invoke().
  • Use __sleep() and __wakeup().
  • Add a readable __toString() method.