包括

2016-03-17 106 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__不断会给你当前文件夹。