View Full Version : Spl_autoloading Cascade Issue

11-11-2012, 02:41 PM
Hi, I am having a problem I am not sure what to think. I am using spl_autoload_register to name multiple autoload functions of my own, this is my test:

function auto_class($class) { include_once "classes/".$class.".php"; }
function auto_iface($iface) { include_once "interfaces/".$iface.".php"; }


This is working as I thought, with the autoload trying first classes then interfaces. The problem is, it always complains when loading an interface!

"Warning: include_once(classes/file.php) [function.include-once]: failed to open stream: No such file or directory in.. etc"

Understandable, since it tries to include_once it as a class first. I can suppress these errors with @ and I wouldn't have display_errors on for a production site but it will fill up my error log with junk mail, and I don't like have warnings! I am thinking, am I using autoload wrong? I would like to require_once, but that will stop my script for any but the first. Do I have to make my own logic to stop this from happening? If so, is file_exists a good method? I heard it can be unreliable, but maybe not in this case.

11-11-2012, 05:08 PM
Simply use file_exists first. If it exists, issue a require, otherwise ignore it and let the method return void.

11-11-2012, 06:57 PM
M'kay, it's doing what I want now that I'm checking the file first. It actually seemed kinda redundant having multiple functions, in this situation.

function auto_load ($obj) {

$incl = ini_get("include_path")."/";
$path = array( 1 => "classes/", 2 => "interfaces/" );
$file = $obj.".php";

if(file_exists( $incl.$path['1'].$file )) { require_once $path['1'].$file; }
elseif(file_exists( $incl.$path['2'].$file )) { require_once $path['2'].$file; }



I'll be playing around with this, seeing how streamline I can make it. Thanks for the tip Fou-Lu.