PHP syntax for calling methods on temporary objects

Is there a way to call a method on a temporary declared object without being forced to assign the 1st object to a variable?

See below:

class Test { private $i = 7; public function get() {return $this->i;} } $temp = new Test(); echo $temp->get(); //ok echo new Test()->get(); //invalid syntax echo {new Test()}->get(); //invalid syntax echo ${new Test()}->get(); //invalid syntax 
+4
source share
10 answers

I use the following workaround when I want this behavior.

I declare this function (in the global scope):

 function take($that) { return $that; } 

Then I use it as follows:

 echo take(new Test())->get(); 
+7
source

What you can do is

 class Test { private $i = 7; public function get() {return $this->i;} public static function getNew() { return new self(); } } echo Test::getNew()->get(); 
+7
source

Why not just do it:

 class Test { private static $i = 7; public static function get() {return self::$i;} } $value = Test::get(); 
+4
source

Unfortunately, you cannot do this. I am just afraid that this is PHP.

+3
source

Not. This is a limitation in the PHP parser.

+3
source

Impossible and why do you even create an object?

An object point is an encapsulation of a unique state. In the example you specified, $i will always be 7, so it makes no sense to create an object, and then get $i from it, and then lose the object in the garbage collector, because there is no reference to the object after $i was returned. A static class, as shown elsewhere, makes much more sense for this. Or closing.

Related topic:

+1
source

I often use this handy little feature

  function make($klass) { $_ = func_get_args(); if(count($_) < 2) return new $klass; $c = new ReflectionClass($klass); return $c->newInstanceArgs(array_slice($_, 1)); } 

Using

 make('SomeCLass')->method(); 

or

 make('SomeClass', arg1, arg2)->foobar(); 
+1
source

This has appeared recently on php internals, and, unfortunately, some influential people (for example, a sniper) who are actively working in PHP development oppose the function . Send an email to php-internals@lists.php.net , tell them that you are an adult programmer.

+1
source

You will probably be interested in the page for the static keyword.

0
source

This is an old question: I just provide an updated answer.

In all supported versions of PHP (starting from 5.4.0, in 2012) you can do this:

 (new Test())->get(); 

See https://secure.php.net/manual/en/migration54.new-features.php ("Access to a class member when instantiating").

0
source

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


All Articles