何时在新类名后添加括号? [英] When to add brackets after new class name?

查看:88
本文介绍了何时在新类名后添加括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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

省略括号和无参数的对象构造函数

没有括号,新类似乎没有打扰。所以,我怀疑括号()的用法是什么。我搜索php手册,没有得到它。

With or without the brackets, the new Class seems not bother. So, I doubt what's the usage of the brackets (). I searched php manual, didn't get it. Could anybody explain?

推荐答案

括号的目的是让你输入你的构造函数可以接受的任何参数。

The purpose of the brackets is for you to enter any arguments that your constructor may accept.

class Example{

    private $str;

    public function __construct($str){
        $this->str = $str;
    }

    public function output(){
        echo $this->str;
    }

}

$ex = new Example; // missing argument error
$ex = new Example('Something');
$ex->output(); // echos "Something"

如果你的类构造函数不接受任何参数,出来。为了好代码,我总是保持括号,无论构造函数是否接受任何参数。

If your class constructor does not accept any arguments, you may leave the brackets out. For good code sake, I always keep the brackets, whether or not the constructor accepts any argument.

大多数来自C#或Java背景的编码人员都会保留括号,因为它们与他们更为相似。

Most coders coming from C# or Java background would keep the parenthesis as it is more familar to them.

这篇关于何时在新类名后添加括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆