note 38901 added to function.class-exists

From: Date: Sat, 10 Jan 2004 23:51:00 +0000
Subject: note 38901 added to function.class-exists
Groups: php.notes 
Request: Send a blank email to php-notes+get-63297@lists.php.net to get a copy of this message
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. ---- Manual Page -- http://www.php.net/manual/en/function.class-exists.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+38901 Delete -- http://master.php.net/manage/user-notes.php?action=delete+38901&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+38901&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#63297) next »