php 中getcwd()、__DIR__、__FILE__ 的作用及區別

php常用獲取文件目錄的方式如下

getcwd() :顯示是 在哪個文件裏調用此文件 的目錄,可用來獲取框架入口文件所在目錄。

__DIR__ :當前內容寫在哪個文件就顯示這個文件目錄。

__FILE__ : 當前內容寫在哪個文件就顯示這個文件目錄+文件名,可使用dirname(__FILE__)獲取當前文件目錄名。


文件目錄結構:./test.php、./a/B.class.php


./test.php文件內容如下:

<?php

spl_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文件內容如下:

<?php
namespace 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/"



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章