代码之家  ›  专栏  ›  技术社区  ›  hbogert

php的包含顺序是什么?

  •  2
  • hbogert  · 技术社区  · 6 年前

    .
    ├── autoload.php
    └── etc
        └── php-lib
            ├── autoload.php
            └── common.php
    
    2 directories, 3 files
    

    以及以下内容:

    cat autoload.php 
    <?php
    echo "I am the wrong autoloader";
    
    cat etc/php-lib/autoload.php 
    <?php
    echo "This is the right one!";
    
    cat etc/php-lib/common.php  
    <?php
    
    include_once('autoload.php');
    

    当我跑的时候

    $ php etc/php-lib/common.php
    

    我将得到以下输出:

    This is the right one!
    

    我之所以这么想,是因为手册规定:

    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. The include construct will emit 
    a warning if it cannot find a file; this is different behavior from 
    require, which will emit a fatal error. 
    

    I am the wrong autoloader
    

    那为什么是 autoload.php 加载而不是 etc/php-lib/autoload.php ?

    事实上,当我分析这个时,include命令似乎比基于手册的预期更奇怪:

    第一种情况,上面描述的所有文件都存在

    getcwd("/home/hvdb/temp2", 4096)        = 17
    lstat("/home/hvdb/temp2/./autoload.php", {st_mode=S_IFREG|0644, st_size=40, ...}) = 0
    lstat("/home/hvdb/temp2/autoload.php", {st_mode=S_IFREG|0644, st_size=40, ...}) = 0
    openat(AT_FDCWD, "/home/hvdb/temp2/autoload.php", O_RDONLY) = 3
    

    自动加载.php 在cwd里。

    ./autoload.php 我得到以下信息:

    getcwd("/home/hvdb/temp2", 4096)        = 17
    lstat("/home/hvdb/temp2/./autoload.php", 0x7fff7f04e880) = -1 ENOENT (No such file or directory)
    lstat("/usr/share/php/autoload.php", 0x7fff7f04e880) = -1 ENOENT (No such file or directory)
    lstat("/home/hvdb/temp2/etc/php-lib/autoload.php", {st_mode=S_IFREG|0644, st_size=38, ...}) = 0
    

    直到那时我才看到PHP(仍然是首先检查 在cwd中),用于include\u目录中设置的目录,然后用于 autoloader.php

    1 回复  |  直到 6 年前
        1
  •  1
  •   icecub    6 年前

    从评论来看,问题是你已经设定了 include_path 在php.ini文件中设置为默认设置。对你来说 .

    这就是为什么在脚本中最好有一个配置文件,在其中创建如下常量:

    PHP>=5.3.0

    define("PATH", __DIR__);
    

    PHP<5.3.0

    define("PATH", dirname(__FILE__));