Junior — Middle
What is the main purpose of the __invoke() function in PHP and in what situations is it used?
sobes.tech AI
Answer from AI
The __invoke() method in PHP allows objects to behave like functions. If this method is defined in a class, an instance of that class can be called as a function.
This is convenient when you need to create objects with a functional interface or implement the "functor" pattern.
Example:
class Greeter {
public function __invoke($name) {
return "Hello, $name!";
}
}
greet = new Greeter();
echo greet("World"); // Outputs: Hello, World!
Thus, __invoke() is used when you want an object to be callable as a function, which simplifies syntax and increases code flexibility.