如果PHP失败,有没有办法从SPL自动加载器中抛出异常?它似乎在PHP 5.2.11下工作。

class SPLAutoLoader{

    public static function autoloadDomain($className) {
        if(file_exists('test/'.$className.'.class.php')){
            require_once('test/'.$className.'.class.php');
            return true;
        }       

        throw new Exception('File not found');
    }

} //end class

//start
spl_autoload_register( array('SPLAutoLoader', 'autoloadDomain') );

try{
    $domain = new foobarDomain();
}catch(Exception $c){
    echo 'File not found';
}

当调用上述代码时,没有例外的迹象,相反,我会得到标准的“致命错误:类'Foobardomain'在BLA中未找到”。脚本的执行终止。

有帮助吗?

解决方案

这不是一个错误,它是 设计决定:

笔记: :抛出异常 __autoload 功能不能抓住 catch 阻止并导致致命错误。

原因是可能有一个以上的自动加载处理程序,在这种情况下,您不希望第一个处理程序抛出异常并绕过第二处理程序。您希望第二个处理程序有机会自动加工其课程。如果您使用使用自动加载功能的库,则不希望它绕过自动加载处理程序,因为它们会在自动加载器中抛出异常。

如果要检查是否可以实例化课程,请使用 class_exists 并通过 true 作为第二个论点(或排除在外, true 是默认值):

if (class_exists('foobarDomain', $autoload = true)) {
    $domain = new foobarDomain();
} else {
    echo 'Class not found';
}

其他提示

根据评论 SPL_AUTOLOAD_REGISTER的文档, ,可以从自动加载器中调用另一个功能,这反过来会引发异常。

class SPLAutoLoader{

    public static function autoloadDomain($className) {
        if(file_exists('test/'.$className.'.class.php')){
            require_once('test/'.$className.'.class.php');
            return true;
        }       
        self::throwFileNotFoundException();
    }

    public static function throwFileNotFoundException()
    {
        throw new Exception('File not found');
    }

} //end class

//start
spl_autoload_register( array('SPLAutoLoader', 'autoloadDomain') );

try{
    $domain = new foobarDomain();
}catch(Exception $c){
    echo 'File not found';
}

这是一个成熟的工厂对象,该对象演示了自动加载,名称支持,非静态实例(带有可变路径)的可可,负载错误的处理和自定义异常。

abstract class AbstractFactory implements \ArrayAccess
{
    protected $manifest;
    function __construct($manifest)
    {
        $this->manifest = $manifest;
    }

    abstract function produce($name);

    public function offsetExists($offset)
    {
        return isset($this->manifest[$offset]);
    }

    public function offsetGet($offset)
    {
        return $this->produce($offset);
    }
    //implement stubs for other ArrayAccess funcs
}


abstract class SimpleFactory extends AbstractFactory {

    protected $description;
    protected $path;
    protected $namespace;

    function __construct($manifest, $path, $namespace = "jj\\") {
        parent::__construct($manifest);
        $this->path = $path;
        $this->namespace = $namespace;
        if (! spl_autoload_register(array($this, 'autoload'), false)) //throws exceptions on its own, but we want a custom one
            throw new \RuntimeException(get_class($this)." failed to register autoload.");
    }

    function __destruct()
    {
        spl_autoload_unregister(array($this, 'autoload'));
    }

    public function autoload($class_name) {
        $file = str_replace($this->namespace, '', $class_name);
        $filename = $this->path.$file.'.php';
        if (file_exists($filename))
            try {
                require $filename; //TODO add global set_error_handler and try clause to catch parse errors
            } catch (Exception $e) {} //autoload exceptions are not passed by design, nothing to do
    }

    function produce($name) {
        if (isset($this->manifest[$name])) {
            $class = $this->namespace.$this->manifest[$name];
            if (class_exists($class, $autoload = true)) {
                return new $class();
            } else throw new \jj\SystemConfigurationException('Factory '.get_class($this)." was unable to produce a new class {$class}", 'SYSTEM_ERROR', $this);
//an example of a custom exception with a string code and data container

        } else throw new LogicException("Unknown {$this->description} {$name}.");
    }

    function __toString() //description function if custom exception class wants a string explanation for its container
    {
        return $this->description." factory ".get_class($this)."(path={$this->path}, namespace={$this->namespace}, map: ".json_encode($this->manifest).")";
    }

}

最后是一个例子:

namespace jj;
require_once('lib/AbstractFactory.php');
require_once('lib/CurrenciesProvider.php'); //base abstract class for all banking objects that are created

class CurrencyProviders extends SimpleFactory
{
    function __construct()
    {
        $manifest = array(
          'Germany' => 'GermanBankCurrencies',
          'Switzerland' => 'SwissBankCurrencies'
        );

        parent::__construct($manifest, __DIR__.'/CurrencyProviders/', //you have total control over relative or absolute paths here
       'banks\');
        $this->description = 'currency provider country name';
    }


}

现在做

$currencies_cache = (new \jj\CurrencyProviders())['Germany'];

或者

$currencies_cache = (new \jj\CurrencyProviders())['Ukraine'];

logicexception(“未知货币提供商国家名称乌克兰”)

如果没有 /货币提供者 /

jj systemConfigurationException('工厂JJ Currency Providers无法生产新的类银行 SwissCurrencies。调试数据:货币提供商国家名称工厂JJ Currency Providers(Path =/var/var/var/www/www/steret/stite /.../ currency -providers/../ ,名称空间=银行,地图:{“德国”:“ dermanbankcurrencies”,“瑞士”:“ swissbankcurrencies”}')

通过足够的努力,该工厂可以扩展以捕获解析错误(如何在PHP中捕获require()或includ()的错误?)并将论据传递给构造函数。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top