您的位置:首页 > 编程语言 > PHP开发

php 中getcwd()、__DIR__、__FILE__ 的作用及区别

2018-03-06 12:29 453 查看
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/"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: