doukong9316 2015-05-22 18:33
浏览 655
已采纳

PHP require_once绝对路径与相对路径(不工作)

Well, I am still very confused how this is possible. Look at the following two lines of code:

Code on Connection.php in class folder:

require_once '../config/constants.php';

require_once dirname(__DIR__).'/config/constants.php';

The second works totally fine, but the first throws the error of:

No such file in ...... on line... in Connection.php

It's getting on my nerves, what is the difference between the two? In my years of programming, I never encountered such problem? Am I missing some points?

If you have any documentation you would like to offer then provide. I would like to have a good foundation of knowledge than just solving problem.

Directory Structure:

enter image description here

  • 写回答

1条回答 默认 最新

  • duanji1899 2015-05-22 18:50
    关注

    ../ denotes the parent directory, compared to the one you're currently in. Therefore, your first line says "go one directory up and look for config/constants.php in there". What you'd want to use with a relative path here is ./ (note the single dot), which denotes your current directory.

    This has little to do with programming in specific, it's more of a file-system thing.

    You can use this as a reference:

    • leading / (no dots, just a slash) means an absolute path
    • leading ./ (single dot) means the current directory
    • leading ../ (two dots) means one directory up
    • no leading dots or slashes is the same thing as with the single dot - relative to the current directory.

    Update (to account for edited question):

    What has something to do with programming and PHP in particular is that what is considered the "current" directory is usually the one where you initially executed the script from. Under a CLI environment, that may vary, but if you're accessing the script via the web that is the location of the PHP file which you have directly accessed. E.g. if you're pointing your browser to example.com/test.php, then wherever 'test.php' is located is the directory you're currently in.

    That can be changed by chdir() of course.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型