PHP中奇怪的类创建[关闭]

I'm working on some PHP code and came across this line, and I'm not sure what the syntax means.

$someclass = (new SomeClass())->someMethod(10);

What is happening here? I'm use to seeing classes being instantiated, and methods being called like this:

$someclass = new SomeClass(); $someClass->someMethod(10);

The class is initiated but there is no reference kept to use the class later. $someClass will contain the value returned by someMethod(10).

That's simply shorthand notation for the same thing. Say you need to call method bar of class Foo. To do so, you need to instantiate Foo:

$foo  = new Foo;
$data = $foo->bar();

But you really have no interest in $foo, you just want $data. The shorthand syntax just instantiates the class and then calls the method, without needing to create and keep the variable $foo:

$data = (new Foo)->bar();

I think you can only do that in php >= 5.4.

The class is instantiated, and then someMethod is called on the new instance. Then the result of someMethod function is stored into $someclass. (The title of this variable is misleading, by the way)

Quick test:

<?php
class SomeClass {
    public function someMethod($val) {
        return $val * 42;
    }
}

$someclass = (new SomeClass())->someMethod(10);
var_dump($someclass);

Output: int(420)

http://ideone.com/Vebt4d

new SomeClass() returns a pointer to a new instance of the class. Rather than assigning that to a variable, the code calls a method in the newly formed instance and returns the value. A handle to the new instance is not kept. If it were C++ it would leak memory, but I'm pretty sure PHP will clean up right away..

This is the same as:

$object1 = new SomeClass();
$someclass = $object1->someMethod(10);

The $someclass should be the return value of someMethod. The actual value and class depends on how someMethod is written.

In some practice, someMethod may return the object instance itself. But it is not a must. Please read someMethod carefully.