包括

2016-03-17 133 views
0

文件我有以下文件結構:包括

www 
|-- MyLibrary 
| |-- Example.class.php 
| +-- someDirectory 
|   +-- somefile.php 
|-- other_file.php 
+-- another_file.php 

我想包括從一個類文件:

<?php 
    class Example { 
     public function test(){ 
      include "someDirectory/somefile.php"; 
     } 
    } 
?> 

,因爲它包括從其他文件時,它會拋出一個錯誤/目錄比類。由於我正在編寫一個庫,因此我不知道文件所在的目錄以及創建實例和'somefile.php'的文件的路徑。

所以我的問題是:有沒有一種方法可以包含'Example.class.php''somefile.php'?

+0

你可以使用PHP autloader系統,這大大簡化了這類問題。 http://php.net/manual/en/language.oop5.autoload.php你也可以使用一個常量,它包含你的應用程序的絕對路徑,並將其前置到包含路徑中。 – kerwan

回答

1

可以在PHP

文件的目錄使用__DIR__不變。如果在include中使用,則返回包含文件的目錄。這相當於dirname(__FILE__)。除非目錄名是根目錄,否則該目錄名沒有結尾斜槓。

https://secure.php.net/manual/en/language.constants.predefined.php

所以這將是:

<?php 
    class Example { 
     public function test(){ 
      include __DIR__."/../someDirectory/somefile.php"; 
     } 
    } 
?> 

有了這個,你使用相對路徑文件。

0

該文件是你可以得到當前路徑

在你工作的結構,可以示例類重寫此:

<?php 
    class Example { 
     public function test(){ 
      include __DIR__ . DIRECTORY_SEPARATOR . "someDirectory/somefile.php"; 
     } 
    } 
?> 

__DIR__不斷會給你當前文件夾。