Is it necessary to Initialize / Declare variable in PHP?(是否需要在 PHP 中初始化/声明变量?)
问题描述
是否需要在循环或函数之前初始化/声明变量?
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.
这篇关于是否需要在 PHP 中初始化/声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否需要在 PHP 中初始化/声明变量?


基础教程推荐
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01