2013-02-24 47 views
-1

如何在下面的代碼中簡化包含的類,而不使用 使用全局包含文件。如何不使用全局包含文件php

enter code here 
<?php 
include "class/class.Prode.php"; 
include "class/class.Groupes.php"; 
include "class/class.Pages.php"; 
include "class/class.Links.php"; 
$prod = new Prode; 
$group = new Groups; 
$page = new Pages; 
$link = new Links; 
?> 

請解釋並參考描述這些的文章。

+0

我相信那會很簡單嗎?除非你想要某種類型的遞歸包含(例如,在類文件夾中包含每個文件) – kennypu 2013-02-24 11:01:44

+2

你需要一個自動加載器。看看spl_autoload_register() – GordonM 2013-02-24 11:01:48

+1

谷歌它,[PHP自動加載](http://bit.ly/ZBnVbp),也見[psr-0](https://github.com/php-fig/fig-standards/blob /master/accepted/PSR-0.md) – Federkun 2013-02-24 11:02:29

回答

1

您需要使用PHP的自動加載功能,我已經在下面爲您添加了一個示例。

function __autoload($class_name) { 
$class_name = strtolower($class_name); // you may need to omit this or rename your files 
$file = "class.{$class_name}.php"; 
$directory = "/path/to/your/class/directory/"; 

if($full_path = recursive_file_exists($file, $directory)) { 
    require($full_path); 
} else { 
    // check if it exists with an s on the end 
      // a nice fallback to cover forgetfulness 
    $file = "class.{$class_name}s.php"; 
    if($full_path = recursive_file_exists($file, $directory)) { 
     require($full_path); 
    } else { 
     die("The file class.{$class_name}.php could not be found in the location ".$directory); 
    } 

希望能幫助你在路上。