Include path and __autoload function in php

I am trying to convert several php scripts to use the __autoload function. Now I can use include and require functions, such as:

require_once('path/to/script.php');

But inside the __autoload function, I cannot use the line above. I have to use this:

require_once('absolute/path/to/script.php');

Why does the __autoload function not seem to use the include path that I specified in php.ini?

+3
source share
4 answers

Do not use __autoload... It has several drawbacks (including a limit of one per run). Use spl_autoload_registerif you are on 5.2+ instead .

So what I usually do is have a class:

class AutoLoader {
    protected static $paths = array(
        PATH_TO_LIBRARIES,
    );
    public static function addPath($path) {
        $path = realpath($path);
        if ($path) {
            self::$paths[] = $path;
        }
    }
    public static function load($class) {
        $classPath = $class; // Do whatever logic here
        foreach (self::$paths as $path) {
            if (is_file($path . $classPath)) {
                require_once $path . $classPath;
                return;
            }
        }
    }
}
spl_autoload_register(array('AutoLoader', 'load'));

, , " " , AutoLoader::AddPath($path);. (IMHO).

. , . , , , , , , . , ...

. (, ), , , require 'foo/bar.php';. define('PATH_ROOT', dirname(__FILE__));, (PATH_LIBRARIES, PATH_TEMPLATES ..). , ... (, , )...

+9

, . :

function __autoload($class) {
    if (file_exists("includes/{$class}.php")) {
        require_once("includes/{$class}.php");
    }
    /**
     * Add any additional directories to search in within an else if statement here
     */
    else {
        // handle error gracefully
    }
}

, script index.php, HTTP- .

0

, __autoload() , , . , __autoload().

0

, . . :

set_include_path('.' . PATH_SEPARATOR . get_include_path());

PHP . ( script - index.php, autoload.php.

, ./path/to/class.php?

0

Source: https://habr.com/ru/post/1755753/


All Articles