0
0
PHPprogramming~5 mins

__invoke for callable objects in PHP

Choose your learning style9 modes available
Introduction

The __invoke method lets you use an object like a function. This makes your code simpler and more flexible.

When you want an object to act like a function for easy calling.
When you want to pass an object as a callback to other functions.
When you want to group related behavior inside an object but call it simply.
When you want to create objects that can be used in places where functions are expected.
Syntax
PHP
class ClassName {
    public function __invoke(...$args) {
        // code to run when object is called like a function
    }
}

$obj = new ClassName();
$obj($args);  // calls __invoke method

The __invoke method can accept any number of arguments.

Calling the object like a function triggers __invoke.

Examples
This example shows an object greeting a person when called like a function.
PHP
<?php
class Greeter {
    public function __invoke($name) {
        return "Hello, $name!";
    }
}
$greet = new Greeter();
echo $greet("Alice");
This example multiplies two numbers using an object called like a function.
PHP
<?php
class Multiplier {
    public function __invoke($a, $b) {
        return $a * $b;
    }
}
$mul = new Multiplier();
echo $mul(4, 5);
Sample Program

This program creates a counter object that increases its count each time it is called like a function.

PHP
<?php
class Counter {
    private int $count = 0;

    public function __invoke(): int {
        return ++$this->count;
    }
}

$counter = new Counter();
echo $counter() . "\n";
echo $counter() . "\n";
echo $counter() . "\n";
OutputSuccess
Important Notes

You can use __invoke to make objects behave like simple functions.

Remember to define __invoke inside your class to use this feature.

Summary

__invoke lets objects be called like functions.

This makes your code cleaner and easier to use in some cases.

Use it when you want objects to act like callable functions.