|
Posted by Chung Leong on 05/07/06 05:39
Paul Czubilinski wrote:
> Hello,
>
> I have a problem with code like this (PHP 5.1.4):
>
> fila A.php:
> =======
>
> include(B.php);
> class document extends obj {
> .........
> }
>
> file B.php:
> =======
>
> $GLOBALS['x']->new we();
>
> function __autoload($class_name) {
> ...here is the code to load classes...
> }
>
> file C.php
> =======
>
> class we extends obj {
>
> private $document;
>
> function __construct() {
> $this->document = new document();
> }
>
> }
>
>
> The problem is that after loading A.php into browser, PHP cannot find
> document class which is defined in the A.php file! The problem is even
> more strange - if document class doesnt extends obj class than
> everything is ok.
>
> (The problem exact is that __autoload special function is called when
> in file C.php constructor of class we try to make the document object
> (all other classes like obj has been already loaded).
>
> Do you have any idea what is wrong with that?
There are limits to PHP's ability to resolve class cross-dependency. I
think you might have bumped into one. I can't quite figure out the load
order of the classes in your example, but I suspect the problem has
something to do with class autoloading. When a class is defined outside
any runtime directives (such as a function), PHP tries to resolve a
class at compile time as well as runtime. Consider the following:
class A extends B {
}
class B {
}
When PHP first encounter A at compile time, there is no way for it to
resolve the class, as it hasn't seen B yet. So it quietly skips over
it, moving on to the definition of B. When PHP runs the code in global
scope, it'll try to resolve A again. This time, B is defined, so
everything is okay.
The situation changes when the definitions are inside a function:
function dingo() {
class A extends B {
}
class B {
}
}
As the function might never be called, PHP cannot resolve either class
at compile time. Both A and B have to be resolved at runtime. Because A
is declared before B, PHP will try to resolve it first--and fail.
[Back to original message]
|