PHP: include() bug, or user error? (Passed filename in IF statement)
Alright so I've already created a PHP bug about this but it was marked as bogus, but I can't help but to believe they didn't read it carefully...
Link to Bug #54042
The error is caused by using an include()
statement in an IF
statement, making the statement believe it's been passed an empty string.
Reviewin开发者_Python百科g the bug will explain everything, including a test script.
Is it a bug, or am I missing something "feature"-wise? This is weird seeing as how assigning the output of include
to a variable and then testing that value works just fine (which would be the workaround).
Well, the documentation says:
Because
include()
is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.<?php // won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('') if (include('vars.php') == 'OK') { echo 'OK'; } // works if ((include 'vars.php') == 'OK') { echo 'OK'; } ?>
So this behaviour is already known and not considered as a bug. You even have an explanation why it works this way:
include
does not need parenthesis, so PHP does not really whether you want to do:
include('vars.php')
or
include(('vars.php') == 'OK')
It seems that it is implemented to interpet it as the latter (something like the longest possible match).
Same goes for
$v = include('foo') . 'bar';
which PHP interprets as
$v = include(('foo') . 'bar');
and tries to load foobar
.
But the solution is also given: Wrap the whole include statement into parenthesis, then there is only one way how PHP can interpret the call:
$v = (include ('foo')) . 'bar';
(Maybe) off topic: You will find similar "issues" in other parts of PHP. Take variable variables:
$obj->$foo['bar'];
PHP does not know whether you want to access the bar
element of the array $foo
and use this value as property name:
$obj->{$foo['bar']};
or if you want to access the bar
element of $obj->$foo
:
{$obj->$foo}['bar'];
In all these cases, there is a default behaviour of the parser. The developers decided for one possibility because they had to. It might not be what you expect, but if you know it, you can deal with it.
This behaviour cannot simply be changed as it might break code that relies on this behaviour.
精彩评论