Home >Backend Development >PHP Tutorial >Detailed explanation of the functions and differences of getcwd(), __DIR__, and __FILE__ in php

Detailed explanation of the functions and differences of getcwd(), __DIR__, and __FILE__ in php

小云云
小云云Original
2018-03-29 09:40:561444browse

本文主要和大家分享php中getcwd()、__DIR__、__FILE__ 的作用和区别详解,希望能帮助到大家。

php常用获取文件目录的方式如下

getcwd() :显示是 在哪个文件里调用此文件 的目录,可用来获取框架入口文件所在目录。

__DIR__ :当前内容写在哪个文件就显示这个文件目录。

__FILE__ : 当前内容写在哪个文件就显示这个文件目录+文件名,可使用dirname(__FILE__)获取当前文件目录名。


文件目录结构:./test.php、./a/B.class.php

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

<?php
spl_autoload_register(&#39;sys_autoload&#39;);
function sys_autoload($class){
	$name = str_replace(&#39;\\&#39;,DIRECTORY_SEPARATOR,dirname(__FILE__).&#39;/&#39;.$class.&#39;.class.php&#39;);
	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/"

The above is the detailed content of Detailed explanation of the functions and differences of getcwd(), __DIR__, and __FILE__ in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn