在php中找不到类

时间:2012-12-14 13:04:02

标签: php namespaces autoload

我的PHP项目结构如下:

--root
 |--dr1
 |   |---dr2
 |        |--testclass.php
 |--start.php
 |--bootstrap.php

testclass.php包含:

 namespace dr1\dr2;

 class testclass { 
     ... 
 }

bootstrap.php包含:

define('DIR_SEP', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__FILE__) . DIR_SEP);

function __autoload($class)
{
    $path = ROOT . str_replace('\\', DIR_SEP, $class);
    $file = $path . '.php';
    if( is_file($file) ) require_once($file);
}

spl_autoload_extensions('.php');
spl_autoload_register('__autoload');

和start.php包含:

$class = 'dr1\dr2\testclass.php';
$obj   = new $class();

当我运行start.php时,我在第5行的dr1\dr2\testclass.php上找不到start.php消息。我无法弄清楚原因。会有人帮忙非常感谢。

2 个答案:

答案 0 :(得分:3)

自动加载器看起来正确,因此问题是类名testclass.php。在您的源文件中,只有testclass而没有.php - 所以如果您调整$class - 变量,它应该有效:

$class = 'dr1\dr2\testclass';
$obj   = new $class();

答案 1 :(得分:1)

要访问您的班级,您可以

$class = new testclass();