Red*_*227 2 php function call line
我看了这个,我知道答案可能涉及使用debug_backtrace(),但我正在努力如何使用它或它究竟是做什么.
基本上,如果这是index.php:
<?php
//some code
//some more code
require "functions.php";
print_line();
//some code
print_line();
?>
Run Code Online (Sandbox Code Playgroud)
和functions.php是:
<?php
function print_line(){
$line="[line that this function was called at]";
print "This function was called from line $line of index.php<br />";
}
?>
Run Code Online (Sandbox Code Playgroud)
设置的正确方法是什么,$line以便输出为:
This function was called from line 7 of index.php
This function was called from line 11 of index.php
Run Code Online (Sandbox Code Playgroud)
debug_backtrace()包含所有嵌套函数调用,一直到当前作用域的索引从0开始(最接近).
所以当你需要调用print_line()的行时,只需要:
<?php
function print_line(){
$backtrace = debug_backtrace();
$line=$backtrace[0]['line'];
print "This function was called from line $line of index.php<br />";
}
Run Code Online (Sandbox Code Playgroud)
或者从PHP 5.4开始:
$line=debug_backtrace()[0]['line'];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1918 次 |
| 最近记录: |