0
0
PhpConceptBeginner · 3 min read

__invoke in PHP: What It Is and How to Use It

__invoke is a special method in PHP that lets you call an object like a function. When you use parentheses after an object, PHP looks for the __invoke method inside that object and runs it automatically.
⚙️

How It Works

Imagine you have a remote control that usually turns on a TV. But what if this remote could also act like a button itself? In PHP, __invoke lets an object behave like a button you can press directly. When you write $object(), PHP checks if the object has a __invoke method and runs it.

This means you don't have to call a specific method by name; just using parentheses after the object triggers the __invoke method. It's like giving your object a special "call me" feature.

💻

Example

This example shows a class with the __invoke method. When we create an object and use parentheses after it, the __invoke method runs and prints a message.

php
<?php
class Greeter {
    public function __invoke($name) {
        echo "Hello, $name!";
    }
}

$greet = new Greeter();
$greet("Alice");
Output
Hello, Alice!
🎯

When to Use

Use __invoke when you want your object to act like a simple function but still keep the power of an object. This is helpful for things like callbacks, small tasks, or when you want to pass objects around that can be "called" easily.

For example, you might create a math operation object that you can call with numbers, or a logger object that you can call to write messages. It makes your code cleaner and more flexible.

Key Points

  • __invoke lets objects be called like functions.
  • It runs automatically when you use parentheses after an object.
  • Useful for callbacks, simple tasks, or flexible code design.
  • Only one __invoke method per class is allowed.

Key Takeaways

__invoke allows an object to be called like a function using parentheses.
It runs automatically when you write $object() if the method exists.
Use it to simplify code that needs callable behavior with object features.
It helps create flexible and clean designs for callbacks and small tasks.