The __invoke Method
The magic method __invoke
allows an instance of a class to be called as a function.
When an object is called as a function, PHP automatically calls this method.
The method can accept parameters and return a value, just like a regular function.
Syntax
class MyClass {
public function __invoke(...$args) {
// implementation
}
}
Example
Let's create a class with the __invoke
method and call the object as a function:
<?php
class Greeter {
public function __invoke($name) {
return "Hello, $name!";
}
}
$greet = new Greeter();
echo $greet('John');
?>
Code execution result:
'Hello, John!'
Example
Using __invoke
with multiple parameters:
<?php
class Calculator {
public function __invoke($a, $b) {
return $a + $b;
}
}
$calc = new Calculator();
echo $calc(5, 3);
?>
Code execution result:
8
Example
Checking if an object is callable using is_callable
:
<?php
class Test {}
$obj1 = new Test();
$obj2 = new class { public function __invoke() {} };
var_dump(is_callable($obj1));
var_dump(is_callable($obj2));
?>
Code execution result:
false
true
See Also
-
the
__construct
method,
which is the class constructor -
the
__toString
method,
which allows an object to be represented as a string