简体   繁体   English

PHP的包括在Windows路径

[英]php include path on windows

I work with PHP on Windows, sience a few days. 我在Windows上使用PHP,这已经有几天了。 The whole time I've been indicated include in the following manner: 指示我的全部时间包括以下方式:

In index.php file: 在index.php文件中:

require ('include/init.inc');

In the directory "include" I stated: 在目录“ include”中,我说:

In init.inc file: 在init.inc文件中:

require ("workbench.inc"); 

But suddenly no longer works. 但是突然之间不再起作用了。 At one time I must also in "init.inc" specify the directory. 一次我还必须在“ init.inc”中指定目录。 Why did it all the time to work, and suddenly no more? 为什么一直都在工作,突然间没有了?

From the PHP documentation: PHP文档中:

Files are included based on the file path given or, if none is given, the include_path specified. 根据给定的文件路径包含文件,如果没有给出文件路径,则基于指定的include_path。 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 如果在include_path中找不到该文件,则include最终将在失败之前检入调用脚本的自身目录和当前工作目录。

So the current working directory (CWD) is important when including other files. 因此,当包含其他文件时, 当前工作目录 (CWD)非常重要。 It can be retrieved by getcwd() . 可以通过getcwd()检索它。

If your directory structure looks like this 如果您的目录结构如下所示

rootdir/
    include/
        init.rc
        workbench.rc
    index.php

then a require('include/init.rc') will only work if rootdir/ is the CWD or is part of the search path. 那么只有require('include/init.rc') rootdir/是CWD或属于搜索路径时, require('include/init.rc')才有效。 Likewise, require('init.inc') assumes the CWD is rootdir/include/ . 同样, require('init.inc')假定CWD为rootdir/include/ Since the current working directory can change, it is idomatic in PHP to use the more robust 由于当前工作目录可以更改,因此使用更强大的功能在PHP中是idomatic的

// in index.php
require(__DIR__ . '/include/init.rc');

// in workbench.rc
require(__DIR__ . '/init.rc');

Then the require will work independent of the CWD. 然后, require将独立于CWD而工作。 This works because the magic constant __DIR__ is replaced by the absolute path to the file that contains the constant without a trailing directory separator, for example 之所以__DIR__是因为魔术常数__DIR__被包含该常数的文件的绝对路径替换,例如没有尾随目录分隔符

  • in index.php , __DIR__ is D:\\path\\to\\rootdir and index.php__DIR__D:\\path\\to\\rootdir
  • in include/init.rc , __DIR__ is D:\\path\\to\\rootdir\\include . include/init.rc__DIR__D:\\path\\to\\rootdir\\include

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM