【问题标题】:class not found in php在 php 中找不到类
【发布时间】:2012-12-02 11:43:18
【问题描述】:

我有一个 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 时,我收到消息 dr1\dr2\testclass.php is not found on start.php on line 5。我不知道为什么。有人会帮忙吗?非常感谢。

【问题讨论】:

  • 该类名为testclass 而不是testclass.php。所以我猜应该是:$class = 'dr1\dr2\testclass'.
  • 您的答案有效,发布它,我会接受。 :) 谢谢。
  • 哇,我见过第一个知道答案但没有尝试在答案中回答的人。

标签: php namespaces autoload


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    要访问您的课程,您可以这样做

    $class = new testclass();

    【讨论】:

    • @aspringaqib 我与class(); 的所有工作都围绕着这一行进行访问,如果我错了,我深表歉意:)
    • 不,伙计,我没有问这个问题。但是如果你今天回答错了,那么很明显在看到你的错误之后你就永远不会回答错了!伙计,冷静一下,这只是一个错误!
    猜你喜欢
    • 2019-11-19
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 2013-01-22
    相关资源
    最近更新 更多