您好,欢迎访问一九零五行业门户网

php中getcwd()、__DIR__、__FILE__ 的作用和区别详解

本文主要和大家分享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/"
以上就是php中getcwd()、__dir__、__file__ 的作用和区别详解的详细内容。
其它类似信息

推荐信息