Autoloader

I was looking at autoloading whilst working with namespaces and I was wondering if anyone could help to fix my autoloader. The code that I had seen was:

<?php
function autoload($className)
{
    $className = ltrim($className, "\ ");
    $fileName  = '';
    $namespace = '';
    if ($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';

    require $fileName;
}

But it never finds the code, my directory structure is:

src
|
|
application - library
|
|
controller - model - view

Take a look at composer autoloader PSR-4, it’s pretty simple and you will understand what you really want to achive.

1 Like

+1 vote for composer’s autoloader. I would strongly recommend going down this route and learning to use composer in your projects. Tis awesome.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.