2015-05-20 75 views
2

是否可以在PHP中使用函数包含文件?我已经尝试了一些东西,但该文件未包含在脚本中。PHP通过函数包含文件

我使用这个功能:

function run($entry_point){ 
    if(!empty($entry_point)){ 
     if(file_exists('assets/controllers/'.$entry_point.'.php')) 
      include 'assets/controllers/'.$entry_point.'.php'; 
     else 
      include 'assets/controllers/home.php'; 
    } 
} 

我的问题了,随着这种功能的指标将不包括$entry_point文件。

Index.php代码:

session_start(); 
run($_GET['location']); 

谢谢!

+0

'是否可以在PHP中使用函数包含文件?'是 – MonkeyZeus

+0

“*如果包含在调用文件中的函数内发生,则包含在调用文件中的所有代码将表现得好像它具有被定义在该函数中。*“[源](http://php.net/manual/en/function.include.php) – Frxstrem

+0

好的,所以它有一个更干净的方式来做到这一点? –

回答

0

首先:你的功能适用于我。确保文件夹的名称是正确的并打开错误报告(error_reporting(E_ALL); ini_set("display_errors", 1);)。

将文件动态添加到脚本中有多种方法。

共同框架使用这样的东西(有点修改您的情况):

function includeScript($path = 'assets/controllers/',$file = 'home'){ 
    require $path . $file . '.php'; 
} 

如果你包括类,请考虑使用autoloader

function my_autoloader($class) { 
    include 'assets/controllers/' . $class . '.php'; 
} 

spl_autoload_register('my_autoloader'); 

这是什么会做的是,只要你想使用一个没有定义的类,它就会自动寻找一个名为assets/controllers/文件夹中类的文件。例如:

// the autoloader would look for assets/controllers/Class1.php 
$obj = new Class1(); 
0

Autoloader将是理想的候选者。不过,你的功能对我来说看起来很好。 您可以对脚本进行以下修改吗?

  1. 打开错误报告并显示错误。详情请参阅Mark的回答。
  2. 在资产之前添加__ DIR __常量。因此,该行将变为:

    if(file_exists(__ DIR __。'/ assets/controllers /'.$ entry_point。'。php')) include __ DIR __。/ assets/controllers /..$ 。入口点 'PHP'; else include __ DIR __。'/ assets/controllers/home.php';

P.S. :请使用大括号作为条件逻辑。它使代码更具可读性。

+0

__ DIR __ === http://php.net/manual/en/language.constants.predefined.php –