PHP名称空间自动加载
我有以下目录结构:PHP名称空间自动加载,php,oop,namespaces,Php,Oop,Namespaces,我有以下目录结构: /var/www/Project1/Project1.php /var/www/Project1/User/UserProfile.php 在Project1.php内部: <?php namespace Project1; set_include_path( __DIR__ ); spl_autoload_extensions('.php'); spl_autoload_register(); use User\UserProfile; $u = new Avat
/var/www/Project1/Project1.php
/var/www/Project1/User/UserProfile.php
在Project1.php内部:
<?php
namespace Project1;
set_include_path( __DIR__ );
spl_autoload_extensions('.php');
spl_autoload_register();
use User\UserProfile;
$u = new Avatar();
...
?>
在UserProfile.php内部:
<?php
namespace Project1\User;
class Avatar{
}
...
?>
当我执行php Project1.php
时,我得到:PHP致命错误:spl_autoload9():无法加载类用户\用户配置文件
我看不出问题。
spl_autoload_register()代码>在没有参数的情况下调用时,只会注册默认的自动加载程序,该程序无法在项目布局中处理名称空间。您必须注册自己的方法才能使其工作。像这样:
spl_autoload_register('my_autoload');
这里是自动加载功能。此函数要求以如下方式存储类:
/path/to/project/Namespace/Classname.php
/path/to/project/Namespace/Subnamespace/Classname.php
您可以将类命名为\Namespaces\Classname
或旧式的名称空间\u Classname
:
function my_autoload ($classname) {
// if the class where already loaded. should not happen
if (class_exists($classname)) {
return true;
}
// Works for PEAR style class names and namespaced class names
$path = str_replace(
array('_', '\\'),
'/',
$classname
) . '.php';
if (file_exists('/path/to/project/' . $tail)) {
include_once 'path/to/project/' . $tail;
return true;
}
return false;
}
请注意,该函数取自我的github包。该包提供了更多功能,包括多个包含路径、路径前缀和静态自动加载(使用预定义的assoc数组类名=>文件名)。如果您愿意,可以使用它;)