Check if a file was included or loaded

后端 未结 12 1171
轻奢々
轻奢々 2020-12-08 13:35

Is there any elegant way to check if a file was included by using include/include_once/require/require_once or if the pag

相关标签:
12条回答
  • 2020-12-08 13:46

    get_included_files() return array where 0 index mean first "included" file. Because direct run mean "include" in this terms, you can simple check first index for equality for __FILE__:

    if(get_included_files()[0] == __FILE__){
        do_stuff();
    }
    

    This can not work on PHP 4, because PHP 4 not add run file in this array.

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

    Here's a different idea. Just include the file whenever you need it. Inside the include file you can decide whether it needs to include the contents:

    <?php
    if (defined("SOME_UNIQUE_IDENTIFIER_FOR_THIS_FILE"))
        return;
    define("SOME_UNIQUE_IDENTIFIER_FOR_THIS_FILE", 1);
    
    // Rest of code goes here
    
    0 讨论(0)
  • 2020-12-08 13:49

    I don't think get_included_files is the perfect solution, what if your main script included some other scripts before the check? My suggestion is to check whether __FILE__ equals realpath($argv[1]):

    <?php
    require('phpunit/Autoload.php');
    
    class MyTests extends PHPUnit_Framework_TestCase
    {
        // blabla...
    }
    
    if (__FILE__ == realpath($argv[0])) {
        // run tests.
    }
    
    0 讨论(0)
  • 2020-12-08 13:50

    Working solution:

    $target_file = '/home/path/folder/file.php'; // or use __FILE__
    
    if ($x=function($e){return str_replace(array('\\'), '/', $e);}) if(in_array( $x($target_file), array_map( $x ,  get_included_files() ) ) )
    {
        exit("Hello, already included !");
    }
    
    0 讨论(0)
  • 2020-12-08 13:52

    you can do this by get_included_files — Returns an array with the names of included or required files and validate against __FILE__

    0 讨论(0)
  • 2020-12-08 13:52

    I appreciate all the answers, but I didn't want to use any one's solution here, so I combined your ideas and got this:

    <?php
        // place this at the top of the file
        if (count(get_included_files()) == 1) define ('TEST_SUITE', __FILE__);
    
        // now I can even include bootstrap which will include other
        // files with similar setups
        require_once '../bootstrap.php'
    
        // code ...
        class Bar {
            ...
        }
        // code ...
    
        if (defined('TEST_SUITE') && TEST_SUITE == __FILE__) {
            // run test suite here  
        }
    ?>
    
    0 讨论(0)
提交回复
热议问题