PHP 类实例化。使用还是不使用括号?

我一直认为,在没有构造函数参数的情况下,创建类实例时,类名后面的括号(大括号)是可选的,可以根据自己的意愿包含或排除它们。

这两种说法是相同的:

$foo = new bar;
$foo = new bar();

我说的对吗? 还是这些括号有什么我不知道的重要意义?

我知道这听起来像一个 RTM 问题,但我已经搜索了一段时间(包括整个 PHP OOP 部分) ,似乎找不到一个直接的答案。

7461 次浏览

They are equivalent. If you are not coding by any code convention, use which you like better. Personally, I like to leave it out, as it is really just clutter to me.

$foo = new bar() would be useful over $foo = new bar if you were passing arguments to the constructor. For example:

class bar {


public $user_id;


function __construct( $user_id ) {
$this->user_id = $user_id
}
}

-

$foo = new bar( $user_id );

Aside from that, and as already mentioned in the accepted answer, there is no difference.