0

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?

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
  • 2
    It's confusing that the \ namespace separator in PHP is the same as the \ directory separator on Windows systems; but the two aren't the same, and shouldn't be used as though the two are synonymous – Mark Baker Jan 19 '13 at 20:47
  • @MarkBaker Can you please suggest a better way? ( I am not being ironic or anything, trying to learn. ) How should it be done? – Koray Tugay Jan 19 '13 at 20:48
  • 1
    Always use the unix / directory separator (which will work with all platforms in PHP) or the built in DIRECTORY_SEPARATOR constant; and only use \ for namespaces.... and look to use an autoloader that follows the psr-0 standard such as https://gist.github.com/221634 for autoloading – Mark Baker Jan 19 '13 at 21:02

1 Answers1

2

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;
Glavić
  • 42,781
  • 13
  • 77
  • 107
  • Thanks, I guess this would work. I do not have a Linux system really, I was just curios. But it is a very good idea to replace '\' with DIRECTORY_SEPERATOR. Thank you. – Koray Tugay Jan 19 '13 at 20:47
  • 1
    Suggestion: all folders/files are saved in lower case on disk (example: frame_work/string_method.php). And autoloader should convert CamelCase to this format (FrameWork > frame_work, StringMethod > string_metod. – Glavić Jan 19 '13 at 20:55
  • Thank you, as I said I am new. – Koray Tugay Jan 19 '13 at 20:58
  • 1
    This is not `a must`, it is `a suggestion` ;-) Welcome to `PHP`. – Glavić Jan 19 '13 at 21:07