← Back to Chapters

PHP OOP __invoke() Method

⚡ PHP OOP __invoke() Method

? Quick Overview

The __invoke() magic method in PHP allows an object to be called like a function. When an object is invoked using parentheses, PHP automatically executes the __invoke() method.

? Key Concepts

  • Objects can behave like functions using __invoke()
  • Method is triggered when an object is called directly
  • Useful for handlers, callbacks, and functional-style objects

? Syntax & Theory

The __invoke() method is declared inside a class and can accept any number of parameters. When the object instance is used as a function, this method executes.

? View Code Example
// Define a class that can be called like a function
class Calculator {
public function __invoke($a, $b) {
return $a + $b;
}
}

// Create object and invoke it like a function
$calc = new Calculator();
echo $calc(5, 10);

? Live Output / Explanation

The object $calc behaves like a function. When $calc(5, 10) is executed, PHP internally calls the __invoke() method and returns the sum 15.

? Interactive Concept

Think of __invoke() as a bridge between object-oriented and functional programming. It allows objects to be passed as callbacks and executed dynamically.

? Use Cases

  • Event handlers and middleware
  • Callback-based architectures
  • Reusable functional objects
  • Dependency injection containers

? Tips & Best Practices

  • Keep __invoke() logic simple and focused
  • Use meaningful parameter names for clarity
  • Ideal for single-responsibility callable objects

? Try It Yourself

  • Create a Multiplier class using __invoke()
  • Pass different numbers and test the output
  • Try using the object as a callback in a function