2013-02-24 44 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); 
    } 

希望能帮助你在路上。