PHP Functors – Function objects in PHP – Aaron McGowan (original) (raw)
Since the release of PHP 5.3, the magical method __invoke() is available to be used within classes. But what does this really mean? Since this new magical method is now available, we are able to invoke instances of a class as a function similar to the available () operator overloading in other languages such as C++. I would imagine that this concept is new to many of PHP programmers if they have not had the joys of programming in languages with operator overloading.
Here is a basic example of a class implementing the __invoke() method in PHP:
class MyClass { public function __invoke() { return 'Hello World'; } }
$obj = new MyClass(); echo $obj(); // Resulting in "Hello World" being printed
Here is a similar example using operator overloads in C++.
class MyClass { public: std::string operator()() { return "Hello World"; } };
int main( void ) { MyClass obj = MyClass(); std::cout << obj(); // Resulting in "Hello World" being printed }
As you can see - this new magical method can now provide us with some create functionality leaving us writing less code. I hope this little tip will help you in creating your next create web application with PHP. Happy coding!