Is defining class variables as null required if they are going to be set during construct?
let say we have class Person($name), Does $name need to be asigned as null as such:
class Person{
var $name = null;
publ开发者_开发百科ic function __construct($name = null){
$this->name = $name;
}
}
Or can var $name = null be eliminated all together?
You can safely leave it as var $name;
. null
will be the default value anyway.
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)
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".
精彩评论