Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create an anonymous object in PHP

Tags:

php

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?

like image 519
Zhigalin - Reinstate CMs Avatar asked Dec 20 '15 01:12

Zhigalin - Reinstate CMs


People also ask

Can an object be anonymous?

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.

Can anonymous classes have constructors PHP?

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.

What is an anonymous class in PHP?

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.

What objects are anonymous objects?

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.


1 Answers

Yes, but you need to add a set of parenthesis, since -> has higher precedence than new:

(new \Controllers\ServiceController)->fbdump();
like image 199
Paul Avatar answered Sep 28 '22 09:09

Paul