Using __invoke()
The __invoke()
magic method gets triggered when the object is being called as a function. The method accepts an optional number of parameters and is is able to return various types of data, or no data at all, as per the following synopsis:
mixed __invoke([ $... ])
If an object class implements the __invoke()
method, we can call the method by specifying parentheses ()
right after the object's name. This type of object is known as a functor or function object.
Note
The Wikipedia page (https://en.wikipedia.org/wiki/Functor) provides more information on the functor.
The following block of code illustrates the simple __invoke()
implementation:
<?php class User { public function __invoke($name, $age) { echo $name . ', ' . $age; } }
The __invoke()
method can be triggered either by using the object instance as a function or by calling call_user_func()
,
$user = new User(); $user('John', 34); // outputs: John, 34 call_user_func($user, 'John', 34); // outputs: John, 34
Using...