2015-05-20 131 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 –