2012-10-06 35 views
0

有時我必須使用include_onceinclude它取決於如何訪問頁面。例如:使用include_once和包括

sales.php

include("class/pdoDatabase.php"); 
include("class/ClassExample.php"); 

$obj = new ClassExample(); 
$obj->getNewItem(1); 

ClassExample.php

include_once("class/pdoDatabase.php"); 

class ClassExample { 
    public function getNewItem($id) { .. } 
    public function addNew($id) { .. } 
} 

// Accessing this file directly via Ajax request 
if (isset($_POST['AddNew'])) { 
    $obj = new ClassExample(); 
    $obj->addNew($_POST['id']); 
} 
} 

如果你訪問sales.php然後將加載include("class/ClassExample.php");,但是我不得不使用include_onceClassExample.php中,因爲pdoDatabase.php可能已在sales.php中加載。 如果您使用POST查詢直接訪問文件到ClassExample.php,這意味着它將不得不加載文件並創建一個對象。

問題: 問題是當您直接訪問ClassExample.php時 - 它找不到class/pdoDatabase.php。它工作正常時,sales.php加載類/ pdoDatabase.php文件

+4

不會將其__變成'include_once'工作嗎?爲什麼要擔心這種差異,當多次包含某些東西幾乎總是一個問題。 –

+1

你爲什麼不製作自動加載器? –

+0

可能是function_exists()? –

回答

1

這不是include_once的問題,幷包括差異。這是相對路徑的問題。 Include總是使用相對於被調用的php文件的路徑。你有這樣的文件結構:

sales.php 
[class] 
- pdoDatabase.php 
- ClassExample.php 
當你調用 sales.php一切正常,但是當你調用 ClassExample.php它試圖找到 class/class/pdoDatabase.php不存在

變化包括線路在ClassExample.php

include_once(dirname(__FILE__)."/pdoDatabase.php"); 

到處都使用相同的模式。

+0

我會問,如果sales.php和ClassExample.php確實在同一個目錄中,但它看起來不是,因此是問題。 –

+0

謝謝彼得。例如,如果位於「Form/Plugin /」中的'ClassExample.php'文件如何?所以在這種情況下,我必須這樣做:'include(dirname(__ DIR__)。'/../../ class/pdoDatabase.php');'? –

+1

@ I'll-Be-Back是的,自PHP 5.3.0以來,有一個新的'__DIR__'常量與'dirname(__ FILE __)'相同,所以你不需要使用'dirname(__ DIR__) '但只是包含(__DD__。'/../../class/pdoDatabase。PHP');'如果你的目標是新的PHP – Petr

0

你做錯了。

而不是手動加載每個類文件,您應該使用自動加載器,即您在應用程序的引導階段進行初始化。沿着線的東西:

$root = __DIR__; 

spl_autoload_register(function($className) use ($root){ 

    $className = str_replace('\\', '/', $className); 
    $filepath = $root . '/' . strtolower($className) . '.php'; 

    if (!file_exists($filepath)) 
    { 
     return false; 
    } 

    require $filepath; 
    return true; 
}); 

要了解更多關於這一點,請閱讀手冊中有關spl_autoload_register()