Call an object method when instantiating

In PHP, why can't I:

class C { function foo() {} } new C()->foo(); 

but I have to do:

 $v = new C(); $v->foo(); 

In all languages ​​I can do this ...

+4
source share
5 answers

In PHP, you cannot call an arbitrary method on a newly created object, for example new Foo()->someMethod();

Sorry, but as it is.

But you could create a job like this:

 <?php class CustomConstructor { public static function customConstruct($methodName) { $obj = new static; //only available in PHP 5.3 or later call_user_method($methodName, $obj); return $obj; } } 

Extend CustomContructor as follows:

 class YourClass extends CustomConstructor { public function someCoolMethod() { //cool stuff } } 

And create them like this:

 $foo = YourClass::customConstruct('someCoolMethod'); 

I have not tested it, but this or something like this should work.

Bugfix: this will only work in PHP 5.3 and later, as late static binding is required.

+4
source

Starting with PHP 5.4 you can do

 (new Foo)->bar(); 

Until then, this is not possible. Cm

But you have several alternatives

An incredibly ugly solution that I cannot explain:

 end($_ = array(new C))->foo(); 

Dimensionless Serialize / Unserialize just to be able to chain

 unserialize(serialize(new C))->foo(); 

Direct approach using Reflection

 call_user_func(array(new ReflectionClass('Utils'), 'C'))->foo(); 

A slightly more robust approach using functions like Factory:

 // global function function Factory($klass) { return new $klass; } Factory('C')->foo() // Lambda PHP < 5.3 $Factory = create_function('$klass', 'return new $klass;'); $Factory('C')->foo(); // Lambda PHP > 5.3 $Factory = function($klass) { return new $klass }; $Factory('C')->foo(); 

The most sensible approach using Factory Method Template Solution:

 class C { public static function create() { return new C; } } C::create()->foo(); 
+15
source

From PHP 5.4 you can: (new Foo())->someMethod();

+8
source

You will not be able to execute code, for example

new C()->foo();

in other languages, at least not as long as the language follows logic exactly. An object is created not only with C() , but with full new C() . Therefore, you should hypothetically be able to execute this code if you include another pair of parentheses: (new C())->foo();

(Be careful: I have not tested above, I just say that this should hypothetically work.)

Most languages ​​(with which I came across) deal with this situation the same way. C, C #, Java, Delphi ...

+1
source

I tried this and succeeded -

 <?php $obj = new test("testFunc"); class test{ function __construct($funcName){ if(method_exists($this, $funcName)){ self::$funcName(); } } function testFunc(){ echo "blah"; return $this; } } ?> 
-1
source

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


All Articles