自动加载器问题未返回 Class

Autoloader issue not returning Class

有问题吗?

Bootloader (Autoloader) 似乎没有正常工作,或者我遗漏了什么。这是简化的代码。

下面的代码returns

Class "Skeleton" does not exist.

在 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>";
}

这里有几个问题:

1)这个line/section不对:

class LoginHeader () {

应该是:

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

2) 您没有正确分配 class。你有:

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

应该是反斜杠:

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

修复反斜杠后,您将在 class 页面上收到语法错误,但您的自动加载器本身工作正常。