Background: I\'m building an automated test framework for a PHP application, and I need a way to efficiently \"stub out\" classes which encapsulate communicatio
It looks like the answer is that class declarations are compile-time, but duplicate class definition errors are run-time at the point in the code that the class is declared. The first time a class definition is in a parsed block, it is immediately made available for use; by returning from an included file early, you aren't preventing class declaration, but you are bailing out before the error is thrown.
For example, here are a bunch of class definitions for Z:
$ cat A.php
test();
return;
class Z {
function test() {
print "Another Z from A.php.\n";
}
}
$ cat Z.php
When A.php
is called, the following is produced:
In Z.php!
array(0) {
}
Modified Z from A.php.
This shows that the declared classes don't change upon entering Z.php
- the Z class is already declared by A.php
further down the file. However, Z.php
never gets a change to complain about the duplicate definition due to the return before the class declaration. Similarly, A.php
doesn't get a chance to complain about the second definition in the same file because it also returns before the second definition is reached.
Conversely, removing the first return;
in Z.php
instead produces:
In Z.php!
Fatal error: Cannot redeclare class Z in Z.php on line 4
By simply not returning early from Z.php
, we reach the class declaration, which has a chance to produce its run-time error.
In summary: class declaration is compile-time, but duplicate definition errors are run-time at the point the class declaration appears in the code.
(Of course, having not confirmed this with the PHP internals, it might be doing something completely different, but the behavior is consistent with my description above. Tested in PHP 5.5.14.)