在php中找不到类
我有一个PHP项目,其结构如下:在php中找不到类,php,namespaces,autoload,Php,Namespaces,Autoload,我有一个PHP项目,其结构如下: --root |--dr1 | |---dr2 | |--testclass.php |--start.php |--bootstrap.php testclass.php包含: namespace dr1\dr2; class testclass { ... } define('DIR_SEP', DIRECTORY_SEPARATOR); define('ROOT', dirname(__FILE__)
--root
|--dr1
| |---dr2
| |--testclass.php
|--start.php
|--bootstrap.php
testclass.php包含:
namespace dr1\dr2;
class testclass {
...
}
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');
$class = 'dr1\dr2\testclass.php';
$obj = new $class();
bootstrap.php包含:
namespace dr1\dr2;
class testclass {
...
}
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');
$class = 'dr1\dr2\testclass.php';
$obj = new $class();
并且start.php包含:
namespace dr1\dr2;
class testclass {
...
}
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');
$class = 'dr1\dr2\testclass.php';
$obj = new $class();
当我运行start.php时,在第5行的
start.php
上找不到消息dr1\dr2\testclass.php
。我不明白为什么。有人能帮忙吗。非常感谢。要访问您的课程,您可以
$class=newtestclass()代码>要访问您的类,您可以执行以下操作
$class=newtestclass()
自动加载程序看起来正确,因此问题在于类名testclass.php
。在源文件中,它只是testclass
,没有.php
-因此,如果您调整$class
-变量,它应该可以工作:
$class = 'dr1\dr2\testclass';
$obj = new $class();
自动加载器看起来是正确的,所以问题是类名testclass.php
。在源文件中,它只是testclass
,没有.php
-因此,如果您调整$class
-变量,它应该可以工作:
$class = 'dr1\dr2\testclass';
$obj = new $class();
该类被命名为testclass
,而不是testclass.php
。所以我想应该是:$class='dr1\dr2\testclass'
。你的答案行得通,把它贴出来,我会接受的。:)谢谢。哇,老兄,我见过第一个知道答案但没有尝试在答案中回答的人。这个类名为testclass
,而不是testclass.php
。所以我想应该是:$class='dr1\dr2\testclass'
。你的答案行得通,把它贴出来,我会接受的。:)谢谢。哇,老兄,我见过第一个知道答案但不想用答案回答的人。@aspringakib我所有的工作都是用class()代码>围绕这一行访问,如果我错了,我道歉:)不,伙计,我没有问这个问题。但是如果你今天回答错了,那么很明显,在看到你的错误之后,你永远不会回答错!伙计,冷静点,这只是个错误@aspringaqib我所有的工作都是使用class()代码>围绕这一行访问,如果我错了,我道歉:)不,伙计,我没有问这个问题。但是如果你今天回答错了,那么很明显,在看到你的错误之后,你永远不会回答错!伙计,冷静点,这只是个错误!