Creating objects on the fly without assigning variables using PHP

I'm just curious to know if creating an object on the fly is possible in PHP. I thought I saw this before. Of course, I can just assign it to a variable, but just wondering if this is possible.

new className()->someMethod(); 

Of course, this causes a syntax error, so obviously this is not the case (if possible). Should I just assign it to a variable, since I really have no problem with this, was I just wondering?


A few more details. Static methods are not really an option, since the class I tried to do is the PHP class ReflectionMethod.

+6
source share
5 answers

This only works if you use a singleton pattern to start an object. If you do not know how to implement singleton-pattern, you will have to search the Internet. But this is how it will work:

 className::getInstance()->someMethod(); 

EDIT

As stated in zerkms, a factory method is also possible:

 class ReflectionFactory { public static function factory($arguments) { return new ReflectionClass($arguments); } } // Then in your code for example ReflectionFactory::factory()->getConstants(); 
+1
source

this use is typical in Java, but not available until PHP 5.3. And now this is a new feature in PHP 5.4. Pls check PHP 5.4 new features . And use should be:

 (new Foo)->bar() 
+9
source

Currently in php it is not possible to create a new object and call its methods in a single expression.

Therefore, obviously, you need to assign it to some variable before.

0
source

You can use the static method for the class without saving the class instance for the variable.

 class testClass{ public static function staticMethod(){ echo "Static method"; } } testClass::staticMethod(); 
0
source

I do not know why PHP does not allow a chain of constructors. If you really need to do this, try something like below with the necessary settings.

 <?php class A { public function b() { echo "a->B is called"; } public static function factory() { return new self; } } $a = A::factory()->b(); ?> 
-1
source

Source: https://habr.com/ru/post/891931/


All Articles