note 38901 deleted from function.class-exists by curt
| From: | curt@php.net | Date: | Fri, 02 Jul 2004 02:33:33 +0000 |
| Subject: | note 38901 deleted from function.class-exists by curt | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-72295@lists.php.net to get a copy of this message | ||
Note Submitter: Jazeps Basko
----
In PHP5 i find that you can't use class_exists() safely in your __autoload() function.
You can use it only in cases the class exists :) In case the class is not yet defined, by using this
function you crush your Apache 2 on Windows or simply get nothing (even no 404 or any other error
page) on Linux.
The crush ain't strange. It's just like an infinite loop, because by __autoload() you are
already looking for class codes but if you call class_exists, PHP seems to do like this 1) checks at
smth like the one we get from get_defined_classes() 2) looks for class code by rules set in your
__autoload()!!!
This is quite logical, but i just god used to thinking that PHP5 crushes whenever I have a syntax
error. Finaly i found out that I had just misspelled class names in class files and that it is the
__autoload() thing that crushes everything.
I did like this:
function __autoload($class) {
$paths = array();
$paths[] = './utils/'.$class.'.php';
$paths[] = './mod/'.$class.'/'.$class.'.php';
$paths[] = './lib/'.$class.'/'.$class.'.php';
$found = false;
for ( $i=0; $i<sizeof($paths) && !$found; $i++ ) {
include_once($paths[$i]);
$found = class_exists($class);
}
if ( !$found ) {
die('Oops, class '.$class.' definition not found!');
}
}
I only lately found out that I have never received the error message! So if you did not include any
file that has the $class code until the end of __autoload(), it looks in __autoload($class) !!!
The solution to this is to rewrite class_exists so that it only checks the array we receive in
get_defined_classes():
function class_defined($class) {
$classes = get_declared_classes();
return in_array($class,$classes);
}
Now i start to think whether it's a bug. Oops.