PHP initialize variable in __construct() vs declaration
i wonder if there is any difference between
class TestClass {
private $_var = "abc";
}
vs
class TestClass {
private $_var;
function __con开发者_Python百科struct() {
$this->_var = "abc";
}
}
i wonder if the latter is the preferred way/better practice? is there any functional difference?
They're effectively the same. I prefer the former, because then there's only one place to look for the value and its default.
On the other hand, if you need to do something dynamic with it or set it to anything other than an array or primitive, you need to use the second form. Notably, you can't use a function call to declare a variable in the first form.
Excellent question! I feel like the first example is more correct, if you already know the initial value of the object's attribute, why would you want to declare it in the constructor?
I feel like the purpose of the constructor is to set attributes that may be variable.
If anything, it seems like a readability thing. I don't know of any performance issues with either method.
I am not aware of any differences in your examples, they both seem to behave the same. if you do both, constructor code overrides the initialization done in the declaration section.
Personally I come from C++ background and in statically typed languages all declarations happen inside the body of the class but outside of any functions, and all initializations and other class prep happen inside the constructor.
When initialization is done as in your first example and there is some code doing something in constructor as well, to me it looks like mixing coding paradigms, so even though it is more verbose, I tend to pick your second example for my own style of code.
精彩评论