note 108678 deleted from keyword.class by sobak
| From: | sobak@php.net | Date: | Sat, 12 Nov 2016 09:36:51 +0000 |
| Subject: | note 108678 deleted from keyword.class by sobak | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-207080@lists.php.net to get a copy of this message | ||
Note Submitter: masonswolf at gmail dot com
----
You can invoke a class above its definitions in some cases, but there are very important exceptions
to this behavior. If your class extends another class, and the interpreter doesn't see the
extended class first, then it won't be added to the symbol table until the code has stepped
through it in runtime. As a result, if you try to invoke it above the definition, you'll get a
"class not found" fatal error.
And those suck.
So, to provide an example, the following will output a fatal error
<?php
Bar::bar();
exit;
class Bar extends Foo { } //will fatal because Foo not seen yet
class Foo {
static function bar() { echo 'yep, this is Foo::bar'; }
}
?>
However, THIS code will work just fine:
<?php
Bar::bar();
exit;
class Foo {
static function bar() { echo 'yep, this is Foo::bar'; }
}
class Bar extends Foo { } //will work because Foo came first
?>
Notice that if you include a file containing the class you will extend, and then extend the class in
the same file as its invocation, you can also get the class not found fatal. This happens even if
the 'include' call happens before the child class's definition.
Eg. the following will also output a fatal error
<?php
include_once('file_with_foo.php');
Bar::bar();
exit;
class Bar extends Foo { }
?>
Hope that clarifies things.