Search code examples
phpnamespacesautoloader

Autoloader issue not returning Class


Problem?

Bootloader (Autoloader) does not seem to be working properly, or I'm missing something. Here is the simplified code.

The code below returns

Class "Skeleton" does not exist.

On index.php file.

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

Solution

  • A couple issues here:

    1) This line/section is not right:

    class LoginHeader () {
    

    Should be:

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

    2) You are not assigning your class correctly. You have:

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

    Should be backslashes:

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

    Once you fix your backslashes, you will get a syntax error on the class page as noted, but your autoloader itself works fine.