繁体   English   中英

php spl_autoload不适用于语法错误的名称空间

[英]php spl_autoload didn't work with namespaces that are syntax errors

我从http://www.php.net/manual/ru/function.spl-autoload.php#92767获得了这个示例

但这会导致错误*致命错误:spl_autoload()[function.spl-autoload]:无法在第18行的C:\\ my_projects \\ site.local \\ www \\ index.php中加载类空间*

的index.php

// Your custom class dir
define('CLASS_DIR', 'oop/classes');

// Add your class dir to include path
set_include_path(get_include_path().PATH_SEPARATOR.CLASS_DIR);


// You can use this trick to make autoloader look for commonly used "My.class.php" type filenames
spl_autoload_extensions('.class.php');

// Use default autoload implementation
spl_autoload_register();

new space/my;

/oop/classes/space/my.class.php

namespace space;
class my{
  public function __construct{
    var_dump('space class was here!');
  }
}

我了解PSR-0,但就我而言,我需要了解内置函数的工作原理

new space/my;

应该

new space\my;

注意:您错过了my.class.php中的__construct ()

以下代码行可能是语法错误,因为您没有像您想象的那样使用语言语法:

new space/my;

让我们拆解一下这里的内容:

  • new - new关键字 ,我们用它实例化一个新对象。
  • space类的名称,这里是字符串"space"
  • / - 除法运算符
  • my - (?未定义)恒定my ,这将导致到字符串"my" ,如果不确定的。

正因为如此(这就是语言),PHP自然会尝试实例化类space ,然后尝试使用字符串"my"来定义它。 例:

$object = new space;
define('my', 0);
$result = $object / my;

由于您使用自动加载并且类space不存在,因此您会看到致命错误。

因此严格来说,语法错误不是在PHP中,而是通过使用错误的语法(此处: /代替\\ ,这是分隔命名空间的正确符号)。

希望这会有所帮助。 请注意,PHP具有松散的类型,因此可以实例化的现有类可能会产生除以零警告的除法

调试spl_autoload_register由于这是内部函数,当不使用自动加载器回调函数使用时,可以出于调试目的而对其进行以下扩展:

spl_autoload_register(funcion($class) {
    echo 'Autoloading class: ', var_dump($class), "\n";
    return spl_autoload($class);
});

另外,您可能想添加扩展而不是覆盖现有扩展:

($current = spl_autoload_extensions()) && $current .= ',';
spl_autoload_extensions($current . '.class.php');
# .inc,.php,.class.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM