2009-11-10 77 views
2

问题是我在与body.html位于同一文件夹中的类中使用方法file _ get _ contents("body.html")。问题是我得到一个错误,说该文件找不到。这是因为我从另一个班级需要使用方法file _ get _ contents("body.html")的文件,并且突然间我必须使用“../body/body.html”作为文件路径。php中的filepath如何工作?

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

这里结束了目录和文件的简短列表:

的lib /主/ main.php
的lib /体/ body.php
的lib /体/ body.html

这是身体.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")

由于改变路径!

回答

8

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

如果index.php被请求,并且包括classes/Foo.php而后者需要包含'body/body.php',则文件范围将为index.php

本质上,current working directory

虽然有一些选择。如果您要包括/开在同一个目录作为当前文件的文件,你可以做这样的事情

file_get_contents(dirname(__FILE__) . '/body.html'); 

或者,你可以在一个恒定的定义基本目录和使用,为您的包容

define('APP_ROOT', '/path/to/app/root/'); 
file_get_contents(APP_ROOT . 'lib/body/body.html'); 
+0

这也帮助了我,谢谢! – ItsMeDom 2014-03-31 03:04:11

1

不,这并不奇怪。

PHP与工作目录一起运行。这通常是“条目”脚本所在的目录。当您执行包含的脚本时,此工作目录不会更改。

如果你想读在当前执行文件的目录的东西,你可以试试

$path = realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR."body.php"; 
1

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

1

您需要定义一个BASEPATH常数项脚本...,然后引用由file_get_contents()相对需要对BASEPATH

所以它可以像所有文件:

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

//and then somewhere else 
file_get_contents(BASEPATH."body/body.html"); 
3

作为除了一个谁与目录名回答(FILE):

PHP 5.3增加了一个DIR魔法不变。所以在PHP 5.3中

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

应该为你做窍门。