dongzao3923 2009-11-10 21:21
浏览 66
已采纳

php中的文件路径如何工作?

The problem is that I use the method file _ get _ contents("body.html") in a class that is in the same folder as body.html. The problem is that I get an error saying that the file could not be found. This is because I from another class require the file that uses the method file _ get _ contents("body.html"), and suddenly I have to use "../body/body.html" as filepath..!

Isn't that a bit strange? The class that calls the method file _ get _ contents("body.html") is in the same folder as body.html, but because the class is required from another class somewhere else, I need a new filepath?!

Here's a short list over directories and files:

lib/main/main.php
lib/body/body.php
lib/body/body.html

This is body.php:

class Body {

 public function getOutput(){
  return file_get_contents("body.html");
 }
}

This is 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();

The thing I ask for is a fix on the error that body.php is in the same folder as body.html but I have to change the path when a another class requires body.php from somewhere else in the method file _ get _ contents("body.html")

Thanks!

  • 写回答

5条回答 默认 最新

  • douchai7891 2009-11-10 21:30
    关注

    The scope of PHP's file-based functions always starts at the point of the first file in the execution stack.

    If index.php is requested, and includes classes/Foo.php which in turn needs to include 'body/body.php', the file scope will be that of index.php.

    Essentially, the current working directory.

    You have some options, though. If you want to include/open a file in the same directory as the current file, you can do something like this

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

    Or, you can define a base directory in a constant and use that for your inclusion

    define( 'APP_ROOT', '/path/to/app/root/' );
    file_get_contents( APP_ROOT . 'lib/body/body.html' );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)