包括来自 class 的文件
Including file from class
我有以下文件结构:
www
|-- MyLibrary
| |-- Example.class.php
| +-- someDirectory
| +-- somefile.php
|-- other_file.php
+-- another_file.php
我想包含来自 class:
的文件
<?php
class Example {
public function test(){
include "someDirectory/somefile.php";
}
}
?>
它会抛出一个错误,因为它是从另一个 file/directory 而不是 class 包含的。由于我正在编写一个库,所以我不知道文件所在的目录以及创建实例的文件的路径和 'somefile.php'.
所以我的问题是: 有没有办法从 'Example.class.php' 中包含 'somefile.php'?
您可以在 PHP
中使用 __DIR__
常量
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__
). This directory name does not have a trailing slash unless it is the root directory.
(https://secure.php.net/manual/en/language.constants.predefined.php)
那就是:
<?php
class Example {
public function test(){
include __DIR__."/../someDirectory/somefile.php";
}
}
?>
这样你就可以使用文件的相对路径了。
您可以获得文件所在的当前路径。
在您正在使用的结构中,您可以将示例 class 重写为:
<?php
class Example {
public function test(){
include __DIR__ . DIRECTORY_SEPARATOR . "someDirectory/somefile.php";
}
}
?>
__DIR__
常量将为您提供当前文件夹。
我有以下文件结构:
www
|-- MyLibrary
| |-- Example.class.php
| +-- someDirectory
| +-- somefile.php
|-- other_file.php
+-- another_file.php
我想包含来自 class:
的文件<?php
class Example {
public function test(){
include "someDirectory/somefile.php";
}
}
?>
它会抛出一个错误,因为它是从另一个 file/directory 而不是 class 包含的。由于我正在编写一个库,所以我不知道文件所在的目录以及创建实例的文件的路径和 'somefile.php'.
所以我的问题是: 有没有办法从 'Example.class.php' 中包含 'somefile.php'?
您可以在 PHP
中使用__DIR__
常量
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(
__FILE__
). This directory name does not have a trailing slash unless it is the root directory.
(https://secure.php.net/manual/en/language.constants.predefined.php)
那就是:
<?php
class Example {
public function test(){
include __DIR__."/../someDirectory/somefile.php";
}
}
?>
这样你就可以使用文件的相对路径了。
您可以获得文件所在的当前路径。
在您正在使用的结构中,您可以将示例 class 重写为:
<?php
class Example {
public function test(){
include __DIR__ . DIRECTORY_SEPARATOR . "someDirectory/somefile.php";
}
}
?>
__DIR__
常量将为您提供当前文件夹。