PHP weirdness
It’s no secret that PHP has some weird behaviors. I just ran into another one that I wasn’t aware of.
Functions in PHP can be defined after they are called, so long as they’re in the same file if memory serves me. The same doesn’t go for functions defined within other functions, though. Observe:
<?php
a();
function a() {
b();
}
function b() {
echo 'foo';
}
That does what you’d expect:
foo
If we now move b() into a(), like so:
<?php
a();
function a() {
b();
function b() {
echo 'foo';
}
}
Watch what happens:
Fatal error: Call to undefined function b() in <file> on line 6
Whereas this works again:
<?php
a();
function a() {
function b() {
echo 'foo';
}
b();
}
Ah well, we all knew PHP was inconsistent, what’s one more inconsistency?
It isn’t *that* shocking, now is it? It is the same in Python, you can’t refer to anything before it is defined. Probably has to do with the interpreted part of the languages.
The stupid thing with PHP is that you can call functions before they’re declared, IIRC they even mention it somewhere in their docs. But it apparently works only in the global scope.