Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial

WBOY
Release: 2016-07-12 08:51:15
Original
947 people have browsed it

The random thoughts of PHP debug_backtrace, phpdebugbacktrace

The test environment for the sample code in this article is APMServ (PHP5.2.6) under Windows

Brief description

As you may all know, there is a function in PHP called debug_backtrace, which can backtrace the calling information of the function, which can be said to be a debugging tool.

Okay, let’s review.

Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial
<span>one();

</span><span>function</span><span> one() {
    two();
}

</span><span>function</span><span> two() {
    three();
}

</span><span>function</span><span> three() {
    </span><span>print_r</span>( <span>debug_backtrace</span><span>() );
}

</span><span>/*</span><span>
输出:
Array
(
    [0] => Array
        (
            [file] => D:\apmserv\www\htdocs\test\debug\index.php
            [line] => 10
            [function] => three
            [args] => Array
                (
                )

        )

    [1] => Array
        (
            [file] => D:\apmserv\www\htdocs\test\debug\index.php
            [line] => 6
            [function] => two
            [args] => Array
                (
                )

        )

    [2] => Array
        (
            [file] => D:\apmserv\www\htdocs\test\debug\index.php
            [line] => 3
            [function] => one
            [args] => Array
                (
                )

        )

)
</span><span>*/</span>
Copy after login
Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial

By the way, a similar function: debug_print_backtrace, the difference is that it will directly print the backtrace information.

Come back and seedebug_backtrace. Judging from the name, the purpose is very clear. It is used by developers for debugging. Until one day I noticed that the file parameter it returned, file represents the calling script source of the function or method (in which script file used). Suddenly I thought, if the current script knows the calling source, can it implement some interesting functions based on the source, such as file permission management, dynamic loading, etc.

Practical combat

Implement magic function

Get the name of the current function or method

Although there are already __FUNCTION__ and __METHOD__ magic constants in PHP, I still want to introduce how to use debug_backtrace to get the current function or method name.

The code is as follows:

Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial
<span>//</span><span>函数外部输出getFuncName的值</span>
<span>echo</span><span> getFuncName();

printFuncName();

</span><span>Object</span>::<span>printMethodName();

</span><span>//</span><span>调用了上面两个函数后,再次在外部输出getFuncName,看看是否有&lsquo;缓存&rsquo;之类的问题</span>
<span>echo</span><span> getFuncName();



</span><span>function</span><span> printFuncName() {
    </span><span>echo</span><span> getFuncName();
}

</span><span>class</span> <span>Object</span><span> {
    </span><span>static</span> <span>function</span><span> printMethodName() {
        </span><span>echo</span><span> getFuncName();
    }
}

</span><span>/*</span><span>*
 * 获取当前函数或者方法的名称
 * 函数名叫getFuncName,好吧,其实method也可以当做function,实在想不出好名字
 * 
 * @return string name
 </span><span>*/</span>
<span>function</span><span> getFuncName() {
    </span><span>$debug_backtrace</span> = <span>debug_backtrace</span><span>();
    </span><span>//</span><span>如果函数名是以下几个,表示载入了脚本,并在函数外部调用了getFuncName
    //这种情况应该返回空</span>
    <span>$ignore</span> = <span>array</span><span>(
        </span>'include',
        'include_once',
        'require',
        'require_once'<span>
    );
    </span><span>//</span><span>第一个backtrace就是当前函数getFuncName,再上一个(第二个)backtrace就是调用getFuncName的函数了</span>
    <span>$handle_func</span> = <span>$debug_backtrace</span>[1<span>];
    </span><span>if</span>( <span>isset</span>( <span>$handle_func</span>['function'] ) && !<span>in_array</span>( <span>$handle_func</span>['function'], <span>$ignore</span><span> ) ) {
        </span><span>return</span> <span>$handle_func</span>['function'<span>];
    }
    </span><span>return</span> <span>null</span><span>;
}


</span><span>//</span><span>输出:
//null
//printFuncName
//printMethodName
//null</span>
Copy after login
Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial

Looks like there’s no problem, it’s fine.

Load relative path file

If you want to load files with relative paths in the project, you must use native methods such as include or require, but now with debug_backtrace, I You can use custom functions to load relative path files.

Create a new project with the following directory structure:

I want to call a custom function in index.php and use relative paths to load package/package.php, and in package.php Use the same method to load _inc_func.php

The codes of the three files are as follows (note the code of index.php and package.php calling the import function):

index.php:

Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial
<?<span>php

import( </span>'./package/package.php'<span> );

</span><span>/*</span><span>*
 * 加载当前项目下的文件
 * 
 * @param string $path 相对文件路径
 </span><span>*/</span>
<span>function</span> import( <span>$path</span><span> ) {
    </span><span>//</span><span>获得backstrace列表</span>
    <span>$debug_backtrace</span> = <span>debug_backtrace</span><span>();
    </span><span>//</span><span>第一个backstrace就是调用import的来源脚本</span>
    <span>$source</span> = <span>$debug_backtrace</span>[0<span>];

    </span><span>//</span><span>得到调用源的目录路径,和文件路径结合,就可以算出完整路径</span>
    <span>$source_dir</span> = <span>dirname</span>( <span>$source</span>['file'<span>] );
    </span><span>require</span> <span>realpath</span>( <span>$source_dir</span> . '/' . <span>$path</span><span> );
}

</span>?>
Copy after login
Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial

package.php:

Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial
<?<span>php

</span><span>echo</span> 'package'<span>;

import( </span>'./_inc_func.php'<span> );

</span>?>
Copy after login
Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial

_inc_func.php:

<?<span>php

</span><span>echo</span> '_inc_func'<span>;

</span>?>
Copy after login

Run index.php:

<span>//</span><span>输出:
//package
//_inc_func</span>
Copy after login

As you can see, I succeeded.

Thoughts: I think this method is very powerful. In addition to relative paths, abstract features such as relative packages and relative modules can be derived based on this idea, which can enhance the role of modularity for some projects.

Manage file calling permissions

I have agreed on a standard: File names with an underscore in front of them can only be called by files in the current directory, which means that such files are "private" in the current directory, and files in other directories are not allowed to load them.

The purpose of this is very clear: to reduce code coupling. In projects, many times some files are only used in specific scripts. But what often happens is that some programmers find that these scripts have functions or classes they need to use, so they load it directly to achieve their own purposes. This approach is very bad. The original purpose of writing these scripts is only to assist in the implementation of certain interfaces, and they do not take other versatility into consideration. In case the interface needs to be refactored internally, these specific script files also need to be modified. However, after the modification, some scripts that seem to have nothing to do with the interface suddenly fail to run. Upon inspection, it turned out that the references to the document were confusing.

规范只是监督作用,不排除有人为了一己私欲而违反这个规范,或者无意中违反了。最好的方法是落实到代码中,让程序自动去检测这种情况。

新建一个项目,目录结构如下。

那么对于这个项目来说,_inc_func.php属于package目录的私有文件,只有package.php可以载入它,而index.php则没有这个权限。

package目录是一个包,package.php下提供了这个包的接口,同时_inc_func.phppackage.php需要用到的一些函数。index.php将会使用这个包的接口文件,也就是package.php

它们的代码如下

index.php:

Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial
<?<span>php

</span><span>header</span>("Content-type: text/html; charset=utf-8"<span>);

</span><span>//</span><span>定义项目根目录</span>
<span>define</span>( 'APP_PATH', <span>dirname</span>( <span>__FILE__</span><span> ) );

import( APP_PATH </span>. '/package/package.php'<span> );
</span><span>//</span><span>输出包的信息</span>
<span>Package_printInfo();

</span><span>/*</span><span>*
 * 加载当前项目下的文件
 * 
 * @param string $path 文件路径
 </span><span>*/</span>
<span>function</span> import( <span>$path</span><span> ) {
    
    </span><span>//</span><span>应该检查路径的合法性</span>
    <span>$real_path</span> = <span>realpath</span>( <span>$path</span><span> );
    </span><span>$in_app</span> = ( <span>stripos</span>( <span>$real_path</span>, APP_PATH ) === 0<span> );
    </span><span>if</span>( <span>empty</span>( <span>$real_path</span> ) || !<span>$in_app</span><span> ) {
        </span><span>throw</span> <span>new</span> <span>Exception</span>( '文件路径不存在或不被允许'<span> );
    }
    
    </span><span>include</span> <span>$real_path</span><span>;
}

</span>?>
Copy after login
Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial

_inc_func.php:

Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial
<?<span>php

</span><span>function</span> _Package_PrintStr( <span>$string</span><span> ) {
    </span><span>echo</span> <span>$string</span><span>;
}

</span>?>
Copy after login
Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial

package.php:

Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial
<?<span>php

</span><span>define</span>( 'PACKAGE_PATH', <span>dirname</span>( <span>__FILE__</span><span> ) );

</span><span>//</span><span>引入私有文件</span>
import( PACKAGE_PATH . '/_inc_func.php'<span> );

</span><span>function</span><span> Package_printInfo() {
    _Package_PrintStr( </span>'我是一个包。'<span> );
}

</span>?>
Copy after login
Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial

运行index.php:

<span>//</span><span>输出:
//我是一个包。</span>
Copy after login

整个项目使用了import函数载入文件,并且代码看起来是正常的。但是我可以在index.php中载入package/_inc_func.php文件,并调用它的方法。

index.php中更改import( APP_PATH . '/package/package.php' );处的代码,并运行:

Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial
import( APP_PATH . '/package/_inc_func.php'<span> );

_Package_PrintStr( </span>'我载入了/package/_inc_func.php脚本'<span> );

</span><span>//</span><span>输出:
//我载入了/package/_inc_func.php脚本</span>
Copy after login
Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial

那么,这时可以使用debug_backtrace检查载入_inc_func.php文件的路径来自哪里,我改动了index.php中的import函数,完整代码如下:

Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial
<span>/*</span><span>*
 * 加载当前项目下的文件
 * 
 * @param string $path 文件路径
 </span><span>*/</span>
<span>function</span> import( <span>$path</span><span> ) {
    
    </span><span>//</span><span>首先应该检查路径的合法性</span>
    <span>$real_path</span> = <span>realpath</span>( <span>$path</span><span> );
    </span><span>$in_app</span> = ( <span>stripos</span>( <span>$real_path</span>, APP_PATH ) === 0<span> );
    </span><span>if</span>( <span>empty</span>( <span>$real_path</span> ) || !<span>$in_app</span><span> ) {
        </span><span>throw</span> <span>new</span> <span>Exception</span>( '文件路径不存在或不被允许'<span> );
    }
    
    </span><span>$path_info</span> = <span>pathinfo</span>( <span>$real_path</span><span> );
    </span><span>//</span><span>判断文件是否属于私有</span>
    <span>$is_private</span> = ( <span>substr</span>( <span>$path_info</span>['basename'], 0, 1 ) === '_'<span> );
    </span><span>if</span>( <span>$is_private</span><span> ) {
        </span><span>//</span><span>获得backstrace列表</span>
        <span>$debug_backtrace</span> = <span>debug_backtrace</span><span>();
        </span><span>//</span><span>第一个backstrace就是调用import的来源脚本</span>
        <span>$source</span> = <span>$debug_backtrace</span>[0<span>];
        
        </span><span>//</span><span>得到调用源路径,用它来和目标路径进行比较</span>
        <span>$source_dir</span> = <span>dirname</span>( <span>$source</span>['file'<span>] );
        </span><span>$target_dir</span> = <span>$path_info</span>['dirname'<span>];
        </span><span>//</span><span>不在同一目录下时抛出异常</span>
        <span>if</span>( <span>$source_dir</span> !== <span>$target_dir</span><span> ) {
            </span><span>$relative_source_file</span> = <span>str_replace</span>( APP_PATH, '', <span>$source</span>['file'<span>] );
            </span><span>$relative_target_file</span> = <span>str_replace</span>( APP_PATH, '', <span>$real_path</span><span> );
            </span><span>$error</span> = <span>$relative_target_file</span> . '文件属于私有文件,' . <span>$relative_source_file</span> . '不能载入它。'<span>;
            </span><span>throw</span> <span>new</span> <span>Exception</span>( <span>$error</span><span> );
        }
    }
    
    </span><span>include</span> <span>$real_path</span><span>;
}</span>
Copy after login
Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial

这时再运行index.php,将产生一个致命错误:

<span>//</span><span>输出:
//致命错误:/package/_inc_func.php文件属于私有文件,/index.php不能载入它。</span>
Copy after login

而载入package.php则没有问题,这里不进行演示。

可以看到,我当初的想法成功了。尽管这样,在载入package.php后,其实在index.php中仍然还可以调用_inc_func.php的函数(package.php载入了它)。因为除了匿名函数,其它函数是全局可见的,包括类。不过这样或多或少可以让程序员警觉起来。关键还是看程序员本身,再好的规范和约束也抵挡不住烂程序员,他们总是会比你‘聪明’。

debug_backtrace的'BUG'

如果使用call_user_func或者call_user_func_array调用其它函数,它们调用的函数里面使用debug_backtrace,将获取不到路径的信息。

例:

Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial
<span>call_user_func</span>('import'<span>);

</span><span>function</span><span> import() {
    </span><span>print_r</span>( <span>debug_backtrace</span><span>() );
}


</span><span>/*</span><span>
输出:
Array
(
    [0] => Array
        (
            [function] => import
            [args] => Array
                (
                )

        )

    [1] => Array
        (
            [file] => F:\www\test\test\index.php
            [line] => 3
            [function] => call_user_func
            [args] => Array
                (
                    [0] => import
                )

        )

)
</span><span>*/</span>
Copy after login
Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial

注意输出的第一个backtrace,它的调用源路径file没有了,这样一来我之前的几个例子将会产生问题。当然可能你注意到第二个backtrace,如果第一个没有就往回找。但经过实践是不可行的,之前我就碰到这种情况,同样会有问题,但是现在无法找回那时的代码了,如果你发现,请将问题告诉我。就目前来说,最好不要使用这种方法,我有一个更好的解决办法,就是使用PHP的反射API。

使用反射

使用反射API可以知道函数很详细的信息,当然包括它声明的文件和所处行数

Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial
<span>call_user_func</span>('import'<span>);

</span><span>function</span><span> import() {
    </span><span>$debug_backtrace</span> = <span>debug_backtrace</span><span>();
    </span><span>$backtrace</span> = <span>$debug_backtrace</span>[0<span>];
    </span><span>if</span>( !<span>isset</span>( <span>$backtrace</span>['file'<span>] ) ) {
        </span><span>//</span><span>使用反射API获取函数声明的文件和行数</span>
        <span>$reflection_function</span> = <span>new</span> ReflectionFunction( <span>$backtrace</span>['function'<span>] );
        </span><span>$backtrace</span>['file'] = <span>$reflection_function</span>-><span>getFileName();
        </span><span>$backtrace</span>['line'] = <span>$reflection_function</span>-><span>getStartLine();
    }
    </span><span>print_r</span>(<span>$backtrace</span><span>);
}

</span><span>/*</span><span>
输出:
Array
(
    [function] => import
    [args] => Array
        (
        )

    [file] => F:\www\test\test\index.php
    [line] => 5
) 
</span><span>*/</span>
Copy after login
Random thoughts about PHP debug_backtrace, phpdebugbacktrace_PHP tutorial

 

可以看到通过使用反射接口ReflectionMethod的方法file又回来了。

类方法的反射接口是ReflectionMethod,获取声明方法同样是getFileName

 

 

总结

在一个项目中,我通常不会直接使用include或者require载入脚本。我喜欢把它们封装到一个函数里,需要载入脚本的时候调用这个函数。这样可以在函数里做一些判断,比如说是否引入过这个文件,或者增加一些调用规则等,维护起来比较方便。

幸好有了这样的习惯,所以我可以马上把debug_backtrace的一些想法应用到整个项目中。

总体来说debug_backtrace有很好的灵活性,只要稍加利用,可以实现一些有趣的功能。但同时我发现它并不是很好控制,因为每次调用任何一个方法或函数,都有可能改变它的值。如果要使用它来做一些逻辑处理(比如说我本文提到的一些想法),需要一个拥有良好规范准则的系统,至少在加载文件方面吧。

 

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1131136.htmlTechArticlePHP debug_backtrace的胡思乱想,phpdebugbacktrace 本文示例代码测试环境是Windows下的APMServ(PHP5.2.6) 简述 可能大家都知道,php中有一个函数叫 d...
Related labels:
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