简体   繁体   English

命名空间和 __autoload

[英]namespace & __autoload

I have a file SQL_config.php:我有一个文件 SQL_config.php:

namespace database;

class SQL_config
{
    private $_server="localhost";
    private $_user="root";
    private $_password="";

    private static $_singleton;
    private $_connection;

    protected function __construct()
    {
        $this->_connection=mysql_connect($this->_server,$this->_user,$this->_password);
    }

    public static function getInstance()
    {
        if(is_null(self::$_singleton))
        {
            self::$_singleton=new SQL_config();
        }

        return self::$_singleton;
    }
}

and index.php:和 index.php:

//namespace database;
//require_once'SQL_config.php';

 function __autoload($class)
    {  
     // convert namespace to full file path  
    //$class = 'database/' . str_replace('\\', '/', $class) . '.php';  
    //require_once($class); 
    require_once  $class . '.php'; 
    }  


$connection=database\SQL_config::getInstance();

and doesn't work.并且不起作用。 Warning: require_once(database\SQL_config.php) [function.require-once]: failed to open stream: No such file or directory in C:\wamp\www\Formular_contact\index.php on line 11. For all version I use it give me error can't somebody help me?警告:require_once(database\SQL_config.php) [function.require-once]: failed to open stream: No such file or directory in C:\wamp\www\Formular_contact\index.php on line 11. 对于我使用的所有版本它给我错误有人不能帮我吗?

define(CLASS_DIR, "/path_to_your_classes_to_load/");

require_once CLASS_DIR . str_replace('\\', '/', ltrim($className, '\\')) . '.php'; 

You need to replace "\" with "/" and add a ".php" to the end of the new class name as it will only get the name without the coma and the extension.您需要将“\”替换为“/”并在新的 class 名称的末尾添加一个“.php”,因为它只会获得没有逗号和扩展名的名称。 And locate the class in the correct folder as shown in the path.并在正确的文件夹中找到 class,如路径所示。

function __autoload($className){
    $newClassName= str_replace("\\", "/", $className) .".php";
    require_once($newClassName);
}

Make sure that you locate the class file in the correct folders such as确保在正确的文件夹中找到 class 文件,例如

./database/SQL_config.php ./数据库/SQL_config.php

If your class is in a folder "classes" Try this instead.如果您的 class 在文件夹“classes”中,请改用此方法。

function __autoload($className){
    $newClassName = "classes/";
    $newClassName .= str_replace("\\", "/", $className) .".php";
    require_once($newClassName);
}

Make sure that you locate the class file in the correct folders such as确保在正确的文件夹中找到 class 文件,例如

./classes/database/SQL_config.php ./classes/database/SQL_config.php

In the code that you have presented - the location of your class file in file structure is also important.在您提供的代码中 - 您的 class 文件在文件结构中的位置也很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM