← Back to Chapters

PHP OOP Call Method (__call)

? PHP OOP Call Method (__call)

? Quick Overview

The PHP OOP __call() magic method is triggered when an inaccessible or non-existing method is called on an object.

? Key Concepts

  • Dynamic method handling
  • Magic methods in PHP
  • Graceful error handling

? Syntax & Theory

The __call() method takes two parameters: the method name and an array of arguments passed to it.

? View Code Example
// Handling dynamic method calls using __call()
<?php
class Student {
    public function __call($name, $arguments) {
        echo "Trying to call method '$name' with arguments: ";
        print_r($arguments);
    }
}

$obj = new Student();
$obj->study("Math", "Science");
?>

? Live Output / Explanation

This will output the method name study and the arguments passed to it, even though the method does not exist.

? Interactive Concept

You can think of __call() as a dynamic dispatcher that intercepts undefined method calls at runtime.

? Use Cases

  • Proxy pattern implementation
  • Logging undefined method calls
  • API method overloading

✅ Tips & Best Practices

  • Use __call() only when dynamic behavior is required.
  • Always validate method names and arguments.
  • Avoid overusing magic methods.

? Try It Yourself

  • Create a Car class without methods.
  • Handle start() and stop() dynamically.
  • Print confirmation messages.