Can I get to work a code like:
new \Controllers\ServiceController()->fbdump();
so I won't have to create a var just to execute a single method?
Object expressions You can define them from scratch, inherit from existing classes, or implement interfaces. Instances of anonymous classes are also called anonymous objects because they are defined by an expression, not a name.
PHP Classes and Objects Anonymous Classes Anonymous classes were introduced into PHP 7 to enable for quick one-off objects to be easily created. They can take constructor arguments, extend other classes, implement interfaces, and use traits just like normal classes can.
As th name suggests, anonymous class is the one which doesn't have name. It is meant for one time use, and if one needs to define a class on the fly. Feature of anonymous class has been introduced since PHP 7 version. Definition of anonymous class lies inside an expression whose result is an object of that class.
An object which has no reference variable is called anonymous object in Java. Anonymous means nameless. If you want to create only one object in a class then the anonymous object is a good approach.
Yes, but you need to add a set of parenthesis, since ->
has higher precedence than new
:
(new \Controllers\ServiceController)->fbdump();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With