如果要在构造期间设置类变量,是否需要将类变量定义为 null?
假设我们有类 Person($name),$name 是否需要指定为 null:
class Person{
var $name = null;
public function __construct($name = null){
$this->name = $name;
}
}
或者 var $name = null 可以一起消除吗?
let say we have class Person($name), Does $name need to be asigned as null as such:
class Person{
var $name = null;
public function __construct($name = null){
$this->name = $name;
}
}
Or can var $name = null be eliminated all together?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以放心地将其保留为
var $name;
。无论如何,null
将是默认值。You can safely leave it as
var $name;
.null
will be the default value anyway.如果您不执行
var $name = null;
并且在分配它之前尝试访问它,您将收到警告/错误。但在你的情况下,除了代码的可读性之外,我不明白为什么需要它(尽管你可以添加关于它的评论)
If you do not do
var $name = null;
and you try to access it before it is assigned you will get warnings/errors.But in your case I do not see why it is needed, except for readability of the code (although you can add a comment about it)
通常最好提前声明文档和 IDE 自动完成功能的属性。然而,这不是 PHP 所需要的。
另外,除非您担心 PHP4(我希望不会),否则使用“public”而不是“var”更合适。
It's usually better to declare the properties beforehand for documentation and IDEs' auto-complete functionality. However, it's not something that's required by PHP.
Also, unless you are worried about PHP4 (I hope not), it's more proper to use "public" instead of "var".