何时在新类名后添加括号? [英] When to add brackets after new class name?
问题描述
没有括号,新类似乎没有打扰。所以,我怀疑括号()
的用法是什么。我搜索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屋!