Last updated on December 10, 2015
Here I present an example and a short tutorial on anonymous classes in PHP.Anonymous classes are new to PHP which are included in PHP7.
An anonymous class is a class without a name. The functionality of the object is no different from that of an object of a named class.Anonymous classes are useful when simple, one-off objects need to be created and when the class does not need to be documented.
Anonymous class use the existing class syntax, without the name – below is the example:
$util->setMessenger(new class { public function sendMessage($msg) { echo $msg; } });
Anonymous class can pass arguments through to their constructors, they can extend other classes and implement interfaces, and use traits just like a normal class can.
someMethod()); // string(3) "bar"
Nesting an anonymous class within another class does not give it access to any private or protected methods or properties of that outer class. In order to use the outer class’ protected properties or methods, the anonymous class can extend the outer class. To use the private or protected properties of the outer class in the anonymous class, they must be passed through its constructor. Serialization is not supported, and will error just as anonymous functions do.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face – we are here to solve your problems.