簡體   English   中英

自動加載和命名空間php

[英]Autoload and Namespaces php

我有這個結構文件:

Classes
      Connection.php
      Admin
           User.php
admin
     index.php

autoload.php

這是我的檔案。 它們很簡單,但我不知道為什么給我錯誤:

這是autoload.php

/*** class Loader ***/
function autoLoader($class){

    $ggFileName = str_replace("\\","/",$class);
    $file = $ggFileName . '.php';

    if (file_exists($file)){

        include $file;
        return true;
    }

        return false;
}

/*** register the loader functions ***/
spl_autoload_register('autoLoader');

我的文件admin / index.php

 include_once('../boostrap.php');

 use \Classes\Admin\User;

 if($_REQUEST['submit'] === 'Login'){

       User::login();

 }



<strong>Login</strong>

<form  name="login" method="post" >

    user:<input type="text" name="user" /> <br/>
    password:<input type="password" name="password" /> <br/>
    <input type="submit" name="submit"  value="Login" />

</form>

我的類/ Admin / User.php --->

 namespace Classes\Admin;

use \Classes\Connection;
use PDO;

class User {

/**
* Auth Login user
*
*/
public static function login(){

    try{

        echo "try to login";

    }catch(\Exception $e){

         echo $e->Message();
    }

}


}

我得到的錯誤是:

 Fatal error: Class 'Classes\Admin\User' not found in /home/germancv/public_html/admin/index.php on line 8

我想我使用的命名空間錯了......

使用PRS-4 Autoload標准命名命名空間,這使得自動加載變得非常容易。

在您的情況下為USER類namespace ProjectName\\Classes\\Admin

組織與命名空間匹配的文件和文件夾。

定義ROOT_URI路徑

例如define('ROOT_URI', 'C:\\Program Files (x86)\\XAMPP\\htdocs\\')

制作自動加載器

spl_autoload_register(function ($class) {
    $file = ROOT_URI. str_replace('\\', '/', $class) .'.php';
    if (file_exists($file)) {
        require $file;
    }
});

如果要使用該類並創建對象

 $user = ProjectName\Admin\User();

要么

use ProjectName\Admin\User as User; 
$user = new User(); 

如果您想要一個類似且簡單的組織命名空間的工作示例

看看我在Github中的代碼,還可以看到init.php文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM