gpt4 book ai didi

php - if 语句的奇怪行为 : always executing else block

转载 作者:可可西里 更新时间:2023-11-01 00:59:46 25 4
gpt4 key购买 nike

friend 们,我怀疑是我还是我的电脑在这里变慢了。

我有以下编码片段:

class Whatever
{
...

private function requireFile($filePath)
{
if(is_array($filePath))
foreach($filePath as $singleFilePath)
if($this->requireFile($singleFilePath))
break;
elseif(($filePath = stream_resolve_include_path($filePath = $filePath . '.php')) !== false)
return require_once $filePath;
}
}

除了是一个丑陋的代码之外,它并没有像预期的那样工作。这里的想法是让这个方法接受字符串和字符串数组作为参数,并且在数组的情况下,递归自身以处理每个字符串。

这是怎么回事,当提供一个数组作为参数时,if 和 elseif block 都会被执行,从而使 PHP 解析器大喊它正在 中发生数组到字符串的转换elseif 行。

我不明白为什么在 if block 周围添加方括号(将它们放在 foreach 周围或 if 内部不会改变任何东西)是让一切都像魅力一样工作,因为 if 下面只有一个语句,因此不需要将它们放在那里:

class Whatever
{
...

private function requireFile($filePath)
{
if(is_array($filePath)) {
foreach($filePath as $singleFilePath)
if($this->requireFile($singleFilePath))
break;
} elseif(($filePath = stream_resolve_include_path($filePath = $filePath . '.php')) !== false)
return require_once $filePath;
}
}

有人可以帮我吗?这段代码有什么问题?

编辑:谢谢大家。我想你的回答证明是我慢了,哈哈哈。远离编程几个月让人们写出疯狂的东西......

最佳答案

没有方括号,PHP 解析器解析与second if 相关的elseif 语句,而不是第一个(外部)。添加括号告诉解析器 elseif 属于第一个 if

PHP 像 Python,其中缩进告诉解析器语句之间的关系。

关于php - if 语句的奇怪行为 : always executing else block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30838771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com