Home > Backend Development > PHP Tutorial > php里如何在函数中获取调用此函数的当前文件名

php里如何在函数中获取调用此函数的当前文件名

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:42:51
Original
1833 people have browsed it

在php获取当前文件名很简单,使用__FILE__常量就是了。但是如果我定义了一个通用函数,而这个每次被调用的时候就要获取当前调用它的是哪个文件,应该怎么办呢?

<code><?php // 这是lib.php
function get_current_file() {
    // ... do something
}
</code></code>
Copy after login
Copy after login
<code><?php // 这是action.php
echo get_current_file();
</code></code>
Copy after login
Copy after login

也就是如上的效果,我调用get_current_file时要获得当前的调用文件比如action.php

这只是个例子,真正使用的时候我不会单纯的去获取文件名,而是要配合一些逻辑,不过这是最重要的一步。

回复内容:

在php获取当前文件名很简单,使用__FILE__常量就是了。但是如果我定义了一个通用函数,而这个每次被调用的时候就要获取当前调用它的是哪个文件,应该怎么办呢?

<code><?php // 这是lib.php
function get_current_file() {
    // ... do something
}
</code></code>
Copy after login
Copy after login
<code><?php // 这是action.php
echo get_current_file();
</code></code>
Copy after login
Copy after login

也就是如上的效果,我调用get_current_file时要获得当前的调用文件比如action.php

这只是个例子,真正使用的时候我不会单纯的去获取文件名,而是要配合一些逻辑,不过这是最重要的一步。

可以试下http://cn2.php.net/manual/zh/function.debug-backtrace.php
里面有个和你要的效果类似的例子,给你摘下如下

<?php
function get_caller_info() {
    $c = '';
    $file = '';
    $func = '';
    $class = '';
    $trace = debug_backtrace();
    if (isset($trace[2])) {
        $file = $trace[1]['file'];
        $func = $trace[2]['function'];
        if ((substr($func, 0, 7) == 'include') || (substr($func, 0, 7) == 'require')) {
            $func = '';
        }
    } else if (isset($trace[1])) {
        $file = $trace[1]['file'];
        $func = '';
    }
    if (isset($trace[3]['class'])) {
        $class = $trace[3]['class'];
        $func = $trace[3]['function'];
        $file = $trace[2]['file'];
    } else if (isset($trace[2]['class'])) {
        $class = $trace[2]['class'];
        $func = $trace[2]['function'];
        $file = $trace[1]['file'];
    }
    if ($file != '') $file = basename($file);
    $c = $file . ": ";
    $c .= ($class != '') ? ":" . $class . "->" : "";
    $c .= ($func != '') ? $func . "(): " : "";
    return($c);
}
Copy after login
Related labels:
php
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template