Re: Why change require_once? A brief explanation of motives
| From: | Johannes Schlüter | Date: | Tue, 17 Jul 2007 11:21:03 +0000 |
| Subject: | Re: Why change require_once? A brief explanation of motives | ||
| References: | 1 2 3 4 5 | Groups: | php.pear.dev |
| Request: | Send a blank email to pear-dev+get-47552@lists.php.net to get a copy of this message | ||
Hi,
On Tue, 2007-07-17 at 12:22 +0200, Lukas Kahwe Smith wrote:
> > Failure to __autoload() a class always results in a fatal error,
> > exceptions thrown in __autoload() cannot be caught. You didn't provide
> > sample code Philippe asked you about [1] and I suppose that's because
> > you simply can't.
>
> ====== Bar.php =======
> class Bar
> {
> public static function factory($driver)
> {
> $class_name = 'Bar_'.$driver;
> if (__autoload($class_name)) {
> return new $class_name();
> }
> throw new Exception('unable to load');
> }
> }
Imo it would be better to trigger __autoload() using class_exists() like
in
class Bar
{
public static function factory($driver)
{
$class_name = 'Bar_'.$driver;
if (class_exists($class_name, true)) {
return new $class_name();
}
throw new Exception('unable to load');
}
}
(the 2nd parameter to class_exists defaults to true, but I think it's
cleaner to have it there...)
Another work-around for throwing Exceptions is by using eval to create a
class - but well, this is only useful if you are sure the class would
never ever exist afterwards:
/** Helper class for highlighting and shorter eval code */
abstract class AutoloadErrorHelper
{
public function __construct()
{
throw new ClassNotFoundException("Class ".get_class()." not found");
}
}
function __autoload($classname)
{
// try to load the class
if (!class_exists($classname, false)) {
eval("class $classname extends AutoloadErrorHelper {}");
}
}
johannes