Introduction
The __invoke method lets you use an object like a function. This makes your code simpler and more flexible.
The __invoke method lets you use an object like a function. This makes your code simpler and more flexible.
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.
<?php class Greeter { public function __invoke($name) { return "Hello, $name!"; } } $greet = new Greeter(); echo $greet("Alice");
<?php class Multiplier { public function __invoke($a, $b) { return $a * $b; } } $mul = new Multiplier(); echo $mul(4, 5);
This program creates a counter object that increases its count each time it is called like a function.
<?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";
You can use __invoke to make objects behave like simple functions.
Remember to define __invoke inside your class to use this feature.
__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.
__invoke method allow an object to do in PHP?__invoke__invoke method is a special method in PHP that allows an object to be called as if it were a function.$obj(). This triggers the __invoke method.__invoke enables function-like calls on objects [OK]__invoke method inside a PHP class?__invoke with two underscores at the start.public function __invoke() {} is correct.$obj = new class { public function __invoke() { return "Hello!"; } };
echo $obj();__invoke method that returns the string "Hello!".$obj() is called, PHP runs the __invoke method and returns "Hello!" which is then echoed.class CallableClass {
public function invoke() {
return "Called!";
}
}
$obj = new CallableClass();
echo $obj();__invoke with double underscores, not just invoke.$obj() looks for __invoke. Since it is missing, PHP throws a fatal error.__invoke to achieve this?class Multiplier {
private int $factor;
public function __construct(int $factor) {
$this->factor = $factor;
}
// Which __invoke method is correct?
// A) public function __invoke(int $num): int { return $num / $this->factor; }
// B) public function __invoke() { return $this->factor; }
// C) public function __invoke(int $num) { return $num + $this->factor; }
// D) public function __invoke(int $num): int { return $num * $this->factor; }
}
$obj = new Multiplier(5);
echo $obj(3);Pass the test and this pattern moves unknown