PHP:在循环中使用变量之前声明变量的正确方法 [英] PHP: Right way to declare variable before use in loop

查看:313
本文介绍了PHP:在循环中使用变量之前声明变量的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内置于循环中的变量.像这样:

I have a variable that is built in loop. Something like:

$str = "";
for($i = 0; $i < 10; $i++) $str .= "something";

如果省略$ str =",我会得到未定义的变量通知,但是我认为php在它第一次看到未声明的变量时会自动声明一个变量?

If $str = "" is ommitted, I get undefined variable notice, but I thought php auto-declare a variable the first time it sees undeclared one?

我该怎么做?

推荐答案

由于将自身的值与另一个值连接在一起,所以会得到未定义的变量.

You get the undefined variable because you're concatenating the value of itself with another value.

相当于

$str = $str . "something";

因此,它不能说初始值是多少.等效于此:

So, it can't say what's the initial value is. It's the equivalent of this:

$str = [undefined value] . "something";

[undefined value]"something"串联的结果是什么?口译员不能说...

What's the result of a concatenation of [undefined value] and "something"? The interpreter can't say...

因此,您必须像以前一样将""放入变量中以初始化变量的值.

So, you have to put "" in the variable first to initiate the variable's value, as you did.

HTH

这篇关于PHP:在循环中使用变量之前声明变量的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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