>我从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 中加载类空间*
/索引.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