tags:

views:

56

answers:

2

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?

A: 

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.

jordanstephens
+3  A: 

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.

Michael Louis Thaler
hmm, i guess that explains it, the 1st method can only be used for simple instantiation, the 2nd is if complex processing if required, eg. function calls or if/else etc
jiewmeng