2

问题是我file _ get _ contents("body.html")在与body.html. 问题是我收到一条错误消息,提示找不到该文件。这是因为我来自另一个班级需要使用该方法的文件,file _ get _ contents("body.html")突然我不得不使用“../body/body.html”作为文件路径..!

这不是有点奇怪吗?调用该方法的类与file _ get _ contents("body.html")位于同一个文件夹中body.html,但是由于其他地方的另一个类需要该类,所以我需要一个新的文件路径?!

这是目录和文件的简短列表:

lib/main/main.php
lib/body/body.php
lib/body/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.phpfile _ get _ contents("body.html")

谢谢!

4

5 回答 5

8

PHP 基于文件的函数的范围总是从执行堆栈中的第一个文件开始。

如果index.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' );
于 2009-11-10T21:30:16.117 回答
3

作为回答 dirname( FILE ) 的人的补充:

PHP 5.3 添加了一个DIR魔法常数。所以在 PHP 5.3

file_get_contents(__DIR__."/body.html");

应该为您解决问题。

于 2009-11-10T21:43:29.713 回答
1

不,这并不奇怪。

PHP 使用工作目录运行。这通常是“入口”脚本所在的目录。当您执行包含的脚本时,该工作目录不会改变。

如果您想在当前执行的文件的目录中读取某些内容,请尝试类似

$path = realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR."body.php";
于 2009-11-10T21:25:38.677 回答
1

如果你想知道当前文件在哪个目录,试试dirname(__FILE__). 你应该可以从那里工作。

于 2009-11-10T21:27:05.170 回答
1

您需要BASEPATH在入口脚本中定义一个常量......然后引用file_get_contents()相对于所需的所有文件BASEPATH

所以它可能是这样的:

define("BASEPATH","/var/www/htdocs/");

//and then somewhere else
file_get_contents(BASEPATH."body/body.html");
于 2009-11-10T21:29:47.117 回答