Home spl_autoload_register on Ubuntu
Reply: 1

spl_autoload_register on Ubuntu

James Wilson
1#
James Wilson Published in 2018-02-13 10:39:38Z

I'm trying to use the spl_autoload_register in PHP to auto load classes in /lib/classes/ directory of my project.

So including this into my boot file

require_once('lib/classes/Autoloader.php');
spl_autoload_register('Autoloader::loader');

Inside Autoloader.php

class Autoloader
{
    public static function loader($class)
    {
        $filename = strtolower($class) . '.php';
        $file ='lib/classes/' . $filename;
        if (!file_exists($file)) {
            echo 'Class '.$class. ' not found'.PHP_EOL;
            return false;
        }
        echo 'Including class '.$class.PHP_EOL;
        include $file;
    }
}

This works perfectly on Windows IIS and loads the classes in lib/classes/ however on Ubuntu it cannot find the classes, so I presume there is something different in the way Ubuntu includes file paths?

Any ideas how I can fix this so it works on Windows and Ubuntu?

Cemal
2#
Cemal Reply to 2018-02-13 10:55:08Z

you can always use absolute paths, however to keep consistency, you can use the function dirname in your boot file and assuming that the folder lib is on the same level relative to your boot file.

define('ROOT_FOLDER',dirname(__FILE__));
require_once(ROOT_FOLDER.'/lib/classes/Autoloader.php');
spl_autoload_register('Autoloader::loader');
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.332468 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO