You might have seen __invoke()
function in famous frameworks or third-party libraries and wondering what this function does, you are in the right place.
The __invoke()
magic method triggered when the object is being called as a function. The method can accept any number of parameters and is able to return mixed data types.
To get triggered this method a Class must contain __invoke()
method among other functions.
For example
<?php class User { public function printName($name) { return $name; } public function __invoke($name, $age) { echo $name . ', ' . $age; } }
So the following code will trigger the __invoke()
method and print the values accordingly.
$user = new User; $user('John', 20); // Outputs John, 20
Another key point is, we can get trigger the __invoke() method using the call_user_func(),
.
An example would be as follows
$user = new User(); call_user_func($user, 'John', 20); // outputs: John, 20
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply