首页 > 解决方案 > (new class())->someMethod() 和 (new Class)->someMethod() 之间的区别

问题描述

我正在尝试找到 (new class())->someMethod()和之间的区别(new Class)->someMethod()。我在本地尝试了一些代码,看起来两者都是一样的,请在这里帮助我

标签: phplaravel

解决方案


class Foo {
    function __construct() {
        echo __METHOD__ . "\n";
    }
    function bar() {
        echo __METHOD__ . "\n";
    }
}

(new Foo())->bar();
(new Foo)->bar();

/**output
Foo::__construct
Foo::bar
Foo::__construct
Foo::bar

*/

其实没有什么不同,只是有一点点不同,

__construct 都被调用


(new class())->someMethod() //does call __construct with parameter when get instance

(new class)->someMethod() // no need call  __construct when get instance

你必须(new class())->foo()按照psr标准的方式使用它

例如



class User
{
    
    private string $name;
    
    public function __construct(string $name)
    {
        $this->name=$name;
    }
}
//in tsis scenarion you have use (new User('john'));

如果不需要 _construct 参数,可以将其用作(new User)->foo().


class User
{

}
//class doesnt want _construct parameters

它必须被称为(new User())。例如,此__construct方法需要一个参数,尽管该参数没有出现。

class User{

    public function __construct()
    {

        print_r(func_get_args());
    }
}


(new User(1,'ff'));

推荐阅读