People, I'm in doubt about whether it is me or my computer that is slow here.
I've following coding piece:
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;
}
}
Besides being an ugly code, it doesn't work as expected. The idea here is to make this method to accept both string and array of strings as parameter and, in case of an array, recurse over itself to work on each of strings.
What is happening it that, when provided an array as parameter, both if and elseif
block are executed, and thus making PHP parser to shout that it's occurring an array to string conversion in elseif
line.
I'm not understanding why adding brackets around if
block (putting them around foreach
or inside if
doesn't change anything) is making everything to work like a charm, since there is only one statement below if
and thus it's not needed to have them there:
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;
}
}
Can somebody help me here? What's wrong in this code?
Edit: thanks folks. I guess your answers proves that it was me the slow one here, hahaha. Months away from programming makes people to write crazy stuff...
Without brackets the PHP parser parses the elseif
statement in relation to the second if
, not the first (outer). Adding brackets tells the parser that the elseif
belongs to the first if
.
PHP is not like Python where indents tells the parser the relation between statements.
I assume that when you put the brackets around the if statement it works. Anyway here's why it would not work.
if($this->requireFile($singleFilePath))
break;
elseif(($filePath = stream_resolve_include_path($filePath = $filePath . '.php')) !== false)
return require_once $filePath;
The elseif
is grouped with the last if
statement encountered in this case the inner if
, you need to add the brackets around the outer if
to explicitly tell the parser that the else if
belongs to the outer if not the inner if
. Indentation makes no difference in PHP.
On another note you have an unnecessary assignment in the elseif branch: $filePath = resolve_include_path($filePath = $filePath . '.php')
can be done without the second assignment $filePath = resolve_include_path($filePath . '.php')
.