Search code examples
phpautoloadautoloader

How does namespaces and autoload work in Linux based systems, PHP?


So here is my code:

<?php

function __autoload($className) {
    $paths = explode(PATH_SEPARATOR, get_include_path());
    $file = $className . '.php';
    foreach ($paths as $path) {
        $combined = $path . DIRECTORY_SEPARATOR . $file;
        if (file_exists($combined)) {
            echo $combined;
            include($combined);
            return;
        }
    }
}

$string = 'Koray';
$string = Framework\StringMethods::_normalize($string);
echo $string;
?>

The above file is called index.php. There is a file called StringMethods.php in the folder under Framework directory..

So my question is here audoloader autoloads: .\Framework\StringMethods.php because I call:

$string = Framework\StringMethods.

so the $file variable actually is= FrameWork\StringMethods. And what I do is to add .php in the end an .\ in the beginning.

But how does Framework\StringMethods will behave in a Linus system? Isn't the directory seperator: "/" in Linux?

So it will try to include: ./Framework\StringMethods.php

If correct, how to code better?


Solution

  • Can you try code bellow? Be careful for for folder/files names, because unix is case-sensitive.

    define('ROOT_PATH', __DIR__ . DIRECTORY_SEPARATOR);
    
    function __autoload($className) {
        $path = str_replace('\\', DIRECTORY_SEPARATOR, $className);
        $file = ROOT_PATH . $path . '.php';
        if (is_file($file)) {
            require_once($file);
        }
    }
    
    $string = 'Koray';
    $string = \Framework\StringMethods::_normalize($string);
    echo $string;