i wonder if there is any difference between
class TestClass {
private $_var = "abc";
}
vs
class TestClass {
private $_var;
function __construct() {
$this->_var = "abc";
}
}
i wonder if the latter is the preferred way/better practice? is there any functional difference?
Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable.
When you declare a variable, you should also initialize it. Two types of variable initialization exist: explicit and implicit. Variables are explicitly initialized if they are assigned a value in the declaration statement. Implicit initialization occurs when variables are assigned a value during processing.
PHP - The __construct FunctionA constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!
Yes, you can also initialize these values using the constructor.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With