php中getcwd()、__DIR__、__FILE__ 的作用和區別詳解

來源:互聯網
上載者:User
本文主要和大家分享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/"

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.