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 中初始化/声明变量?
基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
