Is it necessary to Initialize / Declare variable in PHP?

元气小坏坏 提交于 2021-02-17 18:41:07

问题


This question's purpose is to only gain knowledge or information for me and many like me.

So my question is:

Is it necessary to Initialize / Declare a variable before a loop or a function?

Asking this question is for my confusion because whether I initialize / declare variable before or not my code still works.

I'm sharing a demo code for what I actually mean:

$cars = null;

foreach ($build as $brand) {
     $cars .= $brand . ",";
}

echo $cars;

OR

foreach ($build as $brand) {
     $cars .= $brand . ",";
}

echo $cars;

Both piece of code works same for me, so is necessary to Initialize / Declare a variable at the beginning?


回答1:


PHP does not require it, but it is a good practice to always initialize your variables.

If you don't initialize your variables with a default value, the PHP engine will do a type cast depending on how you are using the variable. This sometimes will lead to unexpected behaviour.

So in short, in my opinion, always set a default value for your variables.

P.S. In your case the value should be set to "" (empty string), instead of null, since you are using it to concatenate other strings.

Edit

As others (@n-dru) have noted, if you don't set a default value a notice will be generated.




回答2:


You had better assign it an empty string $cars = '';, otherwise (in case you have error reporting on) you should see a notice:

Notice: Undefined variable: cars

PHP will assume it was empty and the resultant string will be the same, but you should prefer not to cause an extra overhead caused by a need of logging that Notice. So performance-wise it is better to assign it empty first.

Besides, using editors like Aptana, etc, you may wish to press F3 to see where given variable originated from. And it is so comfortable to have it initialized somewhere. So debugging-wise it is also better to have obvious place of the variable's birth.




回答3:


It depends: If you declare a variable outside a function, it has a "global scope", that means it can only be accessed outside of a function.

If a variable is declared inside a function, it has a "local scope" and can be used only inside that function. (http://www.w3schools.com/php/php_variables.asp)

But it seems that the variable "cars" that you defined outside the function works for your function even without the global keyword...



来源:https://stackoverflow.com/questions/30955639/is-it-necessary-to-initialize-declare-variable-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!