【问题标题】:PHP Include files by a functionPHP 通过函数包含文件
【发布时间】:2015-08-02 03:41:07
【问题描述】:

是否可以在 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']);

谢谢!

【问题讨论】:

  • is it possible to include a file using a function in PHP?是的
  • "如果包含出现在调用文件中的函数内部,则被调用文件中包含的所有代码的行为就像在该函数中定义一样。 " source
  • 好的,有更简洁的方法吗?
  • 最好的方法是使用自动加载器.... google PSR 0PSR 4(取决于您是否使用命名空间)或 spl_autoload

标签: php function file include


【解决方案1】:

首先:你的功能对我有用。确保文件夹名称正确并开启错误报告 (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();

【讨论】:

    【解决方案2】:

    Autoloader 将是这个的理想人选。但是,您的功能对我来说看起来不错。 能否对脚本进行以下修改?

    1. 打开错误报告并显示错误。有关详细信息,请参阅 Mark 的回答。
    2. 在 'assets.所以这条线会变成:

      if(file_exists(__ DIR __.'/assets/controllers/'.$entry_point.'.php')) 包括 __ DIR __.'/assets/controllers/'.$entry_point.'.php'; 别的 包括 __ DIR __.'/assets/controllers/home.php';

    附: : 条件逻辑请使用大括号。它使代码更具可读性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 2013-04-17
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多