【发布时间】:2018-12-09 03:20:27
【问题描述】:
我正在升级一个使用按引用传递的代码库 主要功能
function splitSqlFile(&$ret, $sql)
{
$sql = trim($sql);
$sql_len = strlen($sql);
$char = '';
$string_start = '';
$in_string = false;
for ($i = 0; $i < $sql_len; ++$i) {
$char = $sql[$i];
if ($in_string) {
for (;;) {
$i = strpos($sql, $string_start, $i);
if (!$i) {
$ret[] = $sql;
return true;
}else if ($string_start == '`' || $sql[$i-1] != '\\'){
......
}else {
......
} // end if...elseif...else
} // end for
}
else if ($char == ';') {
$ret[] = substr($sql, 0, $i);
$sql = ltrim(substr($sql, min($i + 1, $sql_len)));
$sql_len = strlen($sql);
if ($sql_len) {
$i = -1;
} else {
// The submited statement(s) end(s) here
return true;
}
}else if (($char == '"') || ($char == '\'') || ($char == '`')) {
$in_string = true;
$string_start = $char;
} // end else if (is start of string)
// for start of a comment (and remove this comment if found)...
else if ($char == '#' || ($char == ' ' && $i > 1 && $sql[$i-2] . $sql[$i-1] == '--')) {
......
if (!$end_of_comment) {
// no eol found after '#', add the parsed part to the returned
// array and exit
$ret[] = trim(substr($sql, 0, $i-1));
return true;
} else {
.....
} // end if...else
} // end else if (is comment)
} // end for
// add any rest to the returned array
if (!empty($sql) && trim($sql) != '') {
$ret[] = $sql;
}
return true;
}
调用函数
$sqlUtility->splitSqlFile($pieces, $sql_query);
foreach ($pieces as $piece)
{
.......
}
如果上面的变量splitSqlFile(&$ret, $sql)前面有“&”,程序确实运行成功,但是如果去掉,现在splitSqlFile($ret, $sql),会开始返回'foreach 提供的参数无效'错误。当我尝试使用“is_array”函数检查它是否为数组时,结果始终为“NULL”。
【问题讨论】:
-
如果我应该使用 splitSqlFile(&$ret, $sql) ,它会工作,但如果它 splitSqlFile($ret, $sql) ,它会返回一个错误
-
嗯,错误是由于 $pieces 是一个死的和空的变量(foreach 会拒绝)。它已经死了,因为一旦你从 $ret 中删除 & ......那么 $ret 就不再是对 $pieces 的引用。因此,您在该函数中对 $ret 所做的任何事情都不会对 $pieces 进行。希望这更清楚?
-
是的,谢谢我现在明白了
-
但是在其他方面纠正问题,有什么建议吗?
-
决定把所有这些都写下来给你。
标签: php foreach pass-by-reference