PHP: Why such weird behaviour when I include a file from another directory which also includes a file?

前端 未结 2 608
我在风中等你
我在风中等你 2020-12-20 07:32

I\'ve never seen anything like this.

File structure:

  • somefolder/base.php
  • includes/stuff.php
  • includes/constants.php

2条回答
  •  心在旅途
    2020-12-20 07:39

    The path used in your includes are not relative to the file the includes are : they are relative to the include_path.

    Which means that using relative paths with includes/requires will generally not do what you expect it to...


    The solution that's generally used is to work with absolute paths ; this way, you are sure what gets included.

    Of course, using absolute paths in your code is bad (it will work on one server, but not another, when your application is deployed to another path) ; so, the solution is to :

    • get the absolute path to the file you're in
    • use that, in addition to a relative path to another file, to include that file.


    The full path to the file you're in can be obtained with __FILE__.

    Which means the directory to the current file (the file that instruction is written in) can be obtained with dirname(__FILE__).

    After that, it's only a matter of writing the correct paths.
    For example, in stuff.php, you'd use :

    require(dirname(__FILE__) . "/constants.php"); 
    

    While, in base.php , you'd use :

    require(dirname(__FILE__) . "/../includes/stuff.php");
    

提交回复
热议问题