【问题标题】:Autoloader issue not returning Class自动加载器问题不返回类
【发布时间】:2016-11-13 00:31:21
【问题描述】:

有问题?

引导加载程序(自动加载程序)似乎无法正常工作,或者我遗漏了一些东西。这是简化的代码。

下面的代码返回

“骨架”类不存在。

在 index.php 文件中。

index.php

<?php

include 'bootloader.php';
use Skeleton\Html\LoginHeader;
$tool = new Skeleton/Html/LoginHeader();

bootloader.php

<?php

function Boot($className) {
        $fileName = '';
        $namespace = '';

        // Sets the include path as the "src" directory
        $includePath = dirname(__FILE__).DIRECTORY_SEPARATOR.'src';

        if (false !== ($lastNsPos = strripos($className, '\\'))) {
            $namespace = substr($className, 0, $lastNsPos);
            $className = substr($className, $lastNsPos + 1);
            $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
        }
        $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
        $fullFileName = $includePath . DIRECTORY_SEPARATOR . $fileName;

        if (file_exists($fullFileName)) {
            require $fullFileName;
        } else {
            echo 'Class "'.$className.'" does not exist.';
        }
    }
    spl_autoload_register('Boot'); // Registers the autoloader

src/Skeleton/Html/LoginHeader.php

<?php

namespace Skeleton\Html;

class LoginHeader () {
    echo "<h1>Login Header OK!</h1>";
}

【问题讨论】:

    标签: php namespaces autoloader


    【解决方案1】:

    这里有几个问题:

    1) 此行/部分不正确:

    class LoginHeader () {
    

    应该是:

    class LoginHeader
        {
            public function __construct()
                {
                    echo "<h1>Login Header OK!</h1>";
                    ...etc
    

    2) 你没有正确分配你的班级。你有:

    $tool = new Skeleton/Html/LoginHeader();
    

    应该是反斜杠:

                --------v----v
    $tool = new Skeleton\Html\LoginHeader();
    

    修复反斜杠后,您会在课程页面上看到语法错误,如前所述,但您的自动加载器本身可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-24
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      相关资源
      最近更新 更多