Why would I use dirname(__FILE__) in an include or include_once statement?

后端 未结 4 1418
梦谈多话
梦谈多话 2020-12-02 07:31

I have seen this:


Why would I ever need to do th

4条回答
  •  猫巷女王i
    2020-12-02 08:08

    Let's say I have a (fake) directory structure like:

    .../root/
            /app
                bootstrap.php
            /scripts
                something/
                    somescript.php
            /public
                index.php
    

    Now assume that bootstrap.php has some code included for setting up database connections or some other kind of boostrapping stuff.

    Assume you want to include a file in boostrap.php's folder called init.php. Now, to avoid scanning the entire include path with include 'init.php', you could use include './init.php'.

    There's a problem though. That ./ will be relative to the script that included bootstrap.php, not bootstrap.php. (Technically speaking, it will be relative to the working directory.)

    dirname(__FILE__) allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap.php resides.

    (Note: since PHP 5.3, you can use __DIR__ in place of dirname(__FILE__).)

    Now, why not just use include 'init.php';?

    As odd as it is at first though, . is not guaranteed to be in the include path. Sometimes to avoid useless stat()'s people remove it from the include path when they are rarely include files in the same directory (why search the current directory when you know includes are never going to be there?).

    Note: About half of this answer is address in a rather old post: What's better of require(dirname(__FILE__).'/'.'myParent.php') than just require('myParent.php')?

提交回复
热议问题