[英]How does filepaths in php work?
问题是我在与body.html
位于同一文件夹的类中使用方法file _ get _ contents("body.html")
。 问题是我收到错误,说找不到该文件。 这是因为我从另一个类需要使用方法file _ get _ contents("body.html")
,突然我必须使用“../body/body.html”作为文件路径..!
这有点奇怪吗? 调用方法file _ get _ contents("body.html")
的类与body.html
位于同一个文件夹中,但由于其他类需要该类,我需要一个新的文件路径?!
这是目录和文件的简短列表:
LIB /主/ main.php
LIB /体/ body.php
LIB /体/ body.html
这是body.php:
class Body {
public function getOutput(){
return file_get_contents("body.html");
}
}
这是main.php:
require '../body/body.php';
class Main {
private $title;
private $body;
function __construct() {
$this->body = new Body();
}
public function setTitle($title) {
$this->title = $title;
}
public function getOutput(){
//prints html with the body and other stuff..
}
}
$class = new Main();
$class->setTitle("Tittel");
echo $class->getOutput();
我问的事情是对的错误修复body.php
是在同一文件夹中body.html
但我有当另一个类,需要改变路径body.php
从别的地方在方法file _ get _ contents("body.html")
谢谢!
PHP基于文件的函数的范围始终从执行堆栈中的第一个文件开始。
如果请求index.php
,并且包括classes/Foo.php
,而classes/Foo.php
又需要包含'body / body.php',则文件范围将是index.php
范围。
基本上, 当前的工作目录 。
不过,你有一些选择。 如果要在与当前文件相同的目录中包含/打开文件,可以执行以下操作
file_get_contents( dirname( __FILE__ ) . '/body.html' );
或者,您可以在常量中定义基目录,并将其用于包含
define( 'APP_ROOT', '/path/to/app/root/' );
file_get_contents( APP_ROOT . 'lib/body/body.html' );
作为回答dirname( FILE )的人的补充:
PHP 5.3增加了一个DIR魔法常量。 所以在PHP 5.3中
file_get_contents(__DIR__."/body.html");
应该为你做的伎俩。
不,这并不奇怪。
PHP使用工作目录运行。 这通常是“条目”脚本所在的目录。执行包含脚本时,此工作目录不会更改。
如果你想阅读当前执行文件的目录中的内容,请尝试类似的方法
$path = realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR."body.php";
如果您想知道当前文件所在的目录,请尝试dirname(__FILE__)
。 你应该能够在那里工作。
您需要在条目脚本中定义BASEPATH
常量...然后引用file_get_contents()
相对于BASEPATH
所需的所有文件
所以它可能是这样的:
define("BASEPATH","/var/www/htdocs/");
//and then somewhere else
file_get_contents(BASEPATH."body/body.html");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.