运行里面有一个函数的循环 [英] Running a loop that has a function inside it
问题描述
这是我的代码:
$ new = array(1,2,3,4);
($ i = 0; $ i <= 3; $ i ++){
$ val = $ new [$ i];
$
$ b $ p
$ b 问题是代码只输出数组中的第一个值。我很困惑,我不想在循环内声明一个函数吗?
解决方案
您的代码结束了致命错误,因为在第二次迭代时,它会尝试重新声明函数 myfunction
。这就是为什么它只打印数组的第一个值。
为了避免致命错误,您可以检查该函数是否已经使用 function_exists()
功能如下:
$ new = array(1,2,3,4);
($ i = 0; $ i <= 3; $ i ++)
{
$ val = $ new [$ i];
if(!function_exists('myfunction'))
{
function myfunction($ value){
//做某事
}
}
echo $ val;
$ b PHP是一种脚本语言,它在语法上是正确的,循环或内部的if语句,但这是一个不好的做法,并可能导致大量的错误后。
最好的方法是声明一个函数在循环外,如果需要,从一个循环内调用它像这样:
<?php
function myfunction($ value){
//做某事
}
$ new = array(1,2,3,4);
($ i = 0; $ i <= 3; $ i ++)
{
$ val = $ new [$ i];
myfunction($ value); //你可能打算在这里传递$ val吗?
echo $ val;
}
I have a problem trying to run a code inside the loop, my loop consist of a function.
Here is my coding:
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++){
$val = $new[$i];
function myfunction($value) {
//Do something
}
echo $val;
}
The problem is the code outputs only the 1st value in my array. I am very confused, am I not suppose to declare a function inside the loop?
解决方案 Your code ends up with Fatal error, since at the second iteration it tries to redeclare function myfunction
. That's why it is printing only first value of array.
In order to avoid that fatal error you can check if that function has been already defined using function_exists()
function like this:
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
if(!function_exists('myfunction'))
{
function myfunction($value) {
//Do something
}
}
echo $val;
}
PHP is a scripting language and it is syntactically correct to declare a function inside for loop or inside if statement, but it is a bad practice and can cause a lot of errors afterwards.
The best way is to declare a function outside loop, and, if needed, call it from within a loop like this:
<?php
function myfunction($value) {
//Do something
}
$new = array(1,2,3,4);
for($i=0;$i<=3;$i++)
{
$val = $new[$i];
myfunction($value); //may you was intended to pass $val here?
echo $val;
}
这篇关于运行里面有一个函数的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!