Helvensteijn.com

Life is like photography
we use the negatives to develop

Jump to menu

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? :P

Published:

Language:
Short URL: hlvn.st/v943

2 replies

  1. PatrickB wrote:

    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.

    Posted on

    • Colin Helvensteijn wrote:

      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. :-P

      Posted on