是否有必要在PHP中初始化/声明变量? [英] Is it necessary to Initialize / Declare variable in PHP?

查看:51
本文介绍了是否有必要在PHP中初始化/声明变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题的目的是仅为我和许多像我一样获得知识或信息.

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

所以我的问题是:

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

问这个问题是为了让我感到困惑,因为我是否在代码之前仍然初始化/声明了变量仍然可以正常工作.

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?

推荐答案

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.

P.S.在您的情况下,该值应设置为"(空字符串),而不是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.

这篇关于是否有必要在PHP中初始化/声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆