note 81306 deleted from function.spl-autoload-register by danbrown
| From: | danbrown@php.net | Date: | Thu, 24 Mar 2011 14:47:53 +0000 |
| Subject: | note 81306 deleted from function.spl-autoload-register by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-178165@lists.php.net to get a copy of this message | ||
Note Submitter: webtweakers at gmail dot com
----
For a while I was using the class autoload solution of sandrejev at gmail dot com, 08-Nov-2006
11:23, on this page http://www.php.net/manual/en/language.oop5.autoload.php.
As it appears, this method works fine most of the time, except in two specific cases:
1. It does not handle static classes correctly (also see the note of ostapk, 19-Dec-2007 02:46, same
page and the article at onphp (s)he refers to).
2. When you accidentally have a variable in your stack that contains single quotes, PHP will choke
with the following cryptic message:
Parse error: parse error, unexpected T_STRING in autoload.inc.php(64) : eval()'d code on line
26
I came up with this solution, which seems to solve these problems:
<?php
// code to set include_path...
class AutoloadException extends Exception { }
class AutoloadClass {
public static function autoload($sClassName) {
$bIsExisting = @include_once($sClassName . '.class.php');
if ($bIsExisting) return;
eval("class $sClassName {
function __construct() {
throw new AutoloadException('Class $sClassName not found');
}
static function __callstatic(\$m, \$args) {
throw new AutoloadException('Class $sClassName not found');
}
}");
}
}
spl_autoload_register(array('AutoloadClass', 'autoload'));
?>
Now, my application, that indeed uses run-time defined (static) classes that are actually allowed
not to exist, runs correctly again. The AutoloadException can be caught to handle this case without
stopping code execution with a Fatal Error.