Home > php教程 > php手册 > body text

解析php dirname()与__FILE__常量的应用

WBOY
Release: 2016-06-13 11:45:49
Original
1400 people have browsed it

__FILE__表示当前所在文件的绝对路径包括文件名,dirname(__FILE__)表示当前文件的绝对路径,basename(__FILE__)表示当前文件的文件名称,dirname(__FILE__)."/f/".basename(__FILE__)则表示当前文件所在目录下的f目录下的,文件名称为dirname(__FILE__)的文件,require表示包含该文件到这个文件。
下面是详解:
1)dirname(__FILE___) 函数返回的是脚本所在在的路径。
     比如文件 b.php 包含如下内容:
         $basedir = dirname(__FILE__);
    ?>
    如果b.php被其他目录里的a.php文件require 或者 include 去引用的话。
    变量$basedir 的内容还是b.php所在的那个文件夹的路径。
    而不是变成a.php文件所在的目录。

2)dirname(__FILE__) 一般会返回文件所的当前目录到系统根目录的一个目录结构。
    不会返回当前的文件名称。
    dirname(__FILE__) 也可能返回一个 . (当前目录)
    [原因是 b.php 文件在 http.conf 或者 PHP 配置开发环境的默认WEB目录下.
    比如 WEB_ROOT 为: "C:/root/www/".]
    b.php文件路径为: "C:/root/www/b.php".

3)使用方法提示,
    如果重复一次可以把目录往上提升一个层次:
    比如:$d = dirname(dirname(__FILE__));
    其实就是把一个目录给dirname()做参数了.因为dirname()返回最后的目录不带\\或者是/
    所以重复使用的时候可以认为 dirname() 把最下层的目录当成文件名来处理了.照常返回
   当前目录的上级目录.这样重复就得到了它的上一级的目录.

4)包含得到上一级目录的文件
    include(dirname(__FILE__).''/../filename

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!