是否需要在 PHP 中初始化/声明变量?

2022-01-18 00:00:00 initialization variables php declaration

是否需要在循环或函数之前初始化/声明变量?

Is it necessary to initialize / declare a variable before a loop or a function?

无论我之前是否初始化/声明变量,我的代码仍然有效.

Whether I initialize / declare variable before or not my code still works.

我正在分享我的实际意思的演示代码:

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

$cars = null;

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

echo $cars;

或者

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

echo $cars;

这两段代码对我来说都是一样的,所以有必要在开始时初始化/声明一个变量吗?

Both pieces of code works same for me, so is it necessary to initialize / declare a variable at the beginning?

推荐答案

PHP 不需要它,但始终初始化变量是一个好习惯.

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

如果您不使用默认值初始化变量,PHP 引擎将根据您使用变量的方式进行类型转换.这有时会导致意外行为.

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.

附:在您的情况下,该值应设置为"(空字符串),而不是 null,因为您使用它来连接其他字符串.

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.

编辑

正如其他人 (@n-dru) 所指出的,如果您不设置默认值,则会生成通知.

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

相关文章