dongye9820 2019-03-05 19:47
浏览 221

require_once:无法打开流

I read on SO and experiment with some answers but my code does not work: I have two classes: C:\Apache24\htdocs\phpdb\classes\dbconnection\mysqlconnection\MySqlConnection.php and C:\Apache24\htdocs\phpdb\classes\utilities\mysqlutilities\CreateTableDemo.php. In CreateTableDemo I have the following code:

    namespace utilities\mysqlutilities;
    use dbconnection\mysqlconnection\MySqlConnection as MSC;
    spl_autoload_register(function($class){
        $class = 'classes\\'.$class.'.php';
        require_once "$class";
    });

I get the following warning:

`Warning: require_once(classes\dbconnection\mysqlconnection\MySqlConnection.php): failed to open stream: No such file or directory in C:\Apache24\htdocs\phpdb\classes\utilities\mysqlutilities\CreateTableDemo.php on line 10`.

I understand the warning, the script does not find the namespaced class in the same folder, so I changed the spl_autoload_register to look for a relative path: __DIR__."\\..\\..\\classes\\.$class.'.php'. I get the

warning: `Warning: require_once(C:\Apache24\htdocs\phpdb\classes\utilities\mysqlutilities\..\..\classes\dbconnection\mysqlconnection\MySqlConnection.php): failed to open stream: No such file or directory in C:\Apache24\htdocs\phpdb\classes\utilities\mysqlutilities\CreateTableDemo.php on line 10`.

I cannot find a way to direct the script to the namespaced class. Thanks in advance for any help.

  • 写回答

2条回答 默认 最新

  • douliang2167 2019-03-05 20:05
    关注

    Create a autoloader-class in a separate file:

    class Autoloader {
        static public function loader($path) {
            $filename = __DIR__.'/classes/'.str_replace("\\", '/', $path).".php";
    
            if (file_exists($filename)) {
                include($filename);
                $aClass = explode('\\', $path);
                $className = array_pop($aClass);           
                if (class_exists($className)) {
                    return TRUE;
                }
            }
            return FALSE;
        }
    }
    spl_autoload_register('Autoloader::loader');
    

    And include it in you index file (or whatever). It will load all your namespaced classes located in folder "classes".

    require_once '/PATH_TO/autoload.php';
    

    BTW: the trick is to replace the backslashes to regular slashes. Works fine for me.

    EDIT: Place the autoloader.php at same level like your "classes" folder is. :-)

    评论

报告相同问题?