PHP class instantiation. To use or not to use the parentheses? [closed]

假装没事ソ 提交于 2019-11-26 01:59:57

问题


I\'ve always assumed that - in the absence of constructor parameters - the parentheses (curly brackets) follow the class name when creating a class instance, were optional, and that you could include or exclude them at your own personal whim.

That these two statements were equal:

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

Am I right? Or is there some significance to the brackets that I am unaware of?

I know this sounds like a RTM question, but I\'ve been searching for a while (including the entire PHP OOP section) and I can\'t seem to find a straight answer.


回答1:


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.




回答2:


$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.



来源:https://stackoverflow.com/questions/1945989/php-class-instantiation-to-use-or-not-to-use-the-parentheses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!