本文主要和大家分享php中getcwd()、__DIR__、__FILE__ 的作用和區別詳解,希望能協助到大家。
php常用擷取檔案目錄的方式如下
getcwd() :顯示是 在哪個檔案裡調用此檔案 的目錄,可用來擷取架構入口檔案所在目錄。
__DIR__ :當前內容寫在哪個檔案就顯示這個檔案目錄。
__FILE__ : 當前內容寫在哪個檔案就顯示這個檔案目錄+檔案名稱,可使用dirname(__FILE__)擷取當前檔案目錄名。
檔案目錄結構:./test.php、./a/B.class.php
./test.php檔案內容如下:
<?phpspl_autoload_register('sys_autoload');function sys_autoload($class){$name = str_replace('\\',DIRECTORY_SEPARATOR,dirname(__FILE__).'/'.$class.'.class.php');if(file_exists($name)){require_once($name);}}var_dump(\a\B::getPath01());var_dump(\a\B::getPath02());var_dump(\a\B::getPath03());./a/B.class.php檔案內容如下:<?phpnamespace a;class B{public $b = [];protected static $instance = null;public static function init($config=[]){if(B::$instance === null){B::$instance = new self;}return self::$instance;}private function __construct($config=[]){}public static function getPath01(){return getcwd().DIRECTORY_SEPARATOR;}public static function getPath02(){return dirname(__FILE__).DIRECTORY_SEPARATOR;}public static function getPath03(){return __DIR__.DIRECTORY_SEPARATOR;}}
運行./test.php,後返回
string(40) "/Library/WebServer/Documents/arithmetic/" string(42) "/Library/WebServer/Documents/arithmetic/a/" string(42) "/Library/WebServer/Documents/arithmetic/a/"