[英]What does this PHP code mean?
require dirname(__FILE__).'/yahooPHP/lib/Yahoo.inc';
該行位於一個目錄中的一個文件中,我在確定如何引用另一目錄中的文件時遇到麻煩。
此表達式是什么意思,是否意味着引用只能位於同一目錄中?
__FILE__
是一個魔術常數 ,對應於其寫入文件的完整路徑。
這意味着dirname(__FILE__)
指向當前文件(寫入該文件的目錄dirname(__FILE__)
的目錄。
因此, dirname(__FILE__).'/yahooPHP/lib/Yahoo.inc'
指向:
yahooPHP
子目錄 yahooPHP
的lib
子目錄 Yahoo.inc
文件放入該lib
目錄。 基本上,您有:
your-file.php
yahooPHP/
lib/
Yahoo.inc
http://php.net/manual/zh/function.dirname.php
分層包含樹的關鍵問題是PHP進程包含相對於原始文件的路徑,而不是當前包含文件的路徑。
一種解決方案是在所有包含路徑之前添加前綴:
<?php str_replace('//','/',dirname( FILE )); ?>這將生成相對於當前文件的基本路徑,然后將允許類似於C / C ++的包含行為。
因此,要在父目錄中包含一個為1的文件:
<?php require_once(str_replace('//','/',dirname( FILE )。'/')。'.. / parent.php'); ?>包含位於同一目錄中的文件:
<?php require_once(str_replace('//','/',dirname( FILE )。'/').'neighbor.php'); ?>包含子目錄中的文件:
<?php require_once(str_replace('//','/',dirname( FILE )。'/').'folder / sub.php'); ?>注意,我們引用的所有路徑都不能以/開頭,並且必須相對於當前文件,以便正確連接。
檢查出規格后 。 這實際上是在PHP腳本中包含指定資源以及檢索父文件夾路徑和字符串串聯的示例。 其工作原理如下:
require = add file to your PHP script (similar to `include`)
dirname() = get the parent directory of specified path
__FILE__ = this will be resolved to absolute path of the current file
.'/yahooPHP/lib/Yahoo.inc' = string concatenation, so this part simply adds file's path to the rest of the string
因此,最后您最終將文件添加到Yahoo.inc文件的路徑指向(應該在相對於父目錄的目錄中找到)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.