What did I see?
I saw in a PHP class using this method __invoke
1
2
3
4
|
public function __invoke(int $errorNumber, string $errorString, string $errorFile, int $errorLine): bool
{
...
}
|
Why using this method?
This magic method is called when user tries to invoke object as a function. Possible use cases may include some approaches like functional programming or some callbacks.
How do people use it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
class Invokable
{
/**
* This method will be called if object will be executed like a function:
*
* $invokable();
*
* Args will be passed as in regular method call.
*/
public function __invoke($arg, $arg, ...)
{
print_r(func_get_args());
}
}
// Example:
$invokable = new Invokable();
$invokable([1, 2, 3]);
// optputs:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
|