Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

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 __construct() {
        $this->_var = "abc";
    }
} 

i wonder if the latter is the preferred way/better practice? is there any functional difference?

question from:https://stackoverflow.com/questions/3209569/php-initialize-variable-in-construct-vs-declaration

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...