Relative include files

前端 未结 3 1569
Happy的楠姐
Happy的楠姐 2020-12-03 12:59

I have a file

workers/activity/bulk_action.php which includes a file

include(\'../../classes/aclass.php\');

Inside aclass.php it d

相关标签:
3条回答
  • 2020-12-03 13:45

    Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include() will finally check in the calling script's own directory and the current working directory before failing.

    You can use dirname(__FILE__) to get a path to the directory where the currently executed script resides:

    include(dirname(dirname(__FILE__)) . '/tcpdf/config/lang/eng.php');
    

    (since PHP 5.3, you can use __DIR__)

    Or, define a constant in the first file that points to the root directory and use it in your includes.

    0 讨论(0)
  • 2020-12-03 13:46

    You would be way better off by setting a proper value to the include_path and then use paths relative to this directory.

    set_include_path(
        get_include_path() .
        PATH_SEPARATOR .
        realpath(__DIR__ . '/your/lib')
    );
    
    include 'tcpdf/config/lang/eng.php';
    include 'classes/aclass.php';
    

    I also suggest you take a look at autoloading. This will make file includes obsolete.

    0 讨论(0)
  • 2020-12-03 13:55

    You can adapt the second include with:

    include (__DIR__.'/../tcpdf/config/lang/eng.php');
    

    The magic constant __DIR__ refers to the current .php file, and by appending the relative path after that, will lead to the correct location.

    But it only works since PHP5.3 and you would have to use the dirname(__FILE__) construct instead if you need compatibility to older setups.

    0 讨论(0)
提交回复
热议问题