PHP 是我从 echo 或 sprintf 调用的函数

PHP is my function called from echo, or sprintf

我想看看调用函数的地方。

函数是在echo还是sprintf中调用的?然后return,否则回显内容

我得到了这个代码(test.php):

<?php
function __($str = '')
{
    // who is my parent?
    $parent=debug_backtrace();

    if ( isset ( $parent[1] ) )
        $parent = $parent[1]['function']; //Did it!
    else
        $parent = debug_backtrace()[1]['function']; //Try

    if ( empty ( $parent ) )
        $parent = "ERROR!";

    return sprintf("[%s] %s.%s", $parent, $str, PHP_EOL);
}

__('does nothing');
echo __('test from echo #1');
echo(__('test from echo #2'));
echo sprintf(__('test from sprintf #1'));
echo(sprintf(__('test from sprintf #2')));
?>

当我在终端输入时,我得到的是:

WDGMBP:Test Wes$ php test.php 
[ERROR!] test from echo #1.
[ERROR!] test from echo #2.
[ERROR!] test from sprintf #1.
[ERROR!] test from sprintf #2.

(p.s。来自网络相同)

我的 PHP 版本是:

WDGMBP:BIHappyV3 Wes$ php -v
PHP 5.5.27 (cli) (built: Aug 22 2015 18:20:44) 
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies

您对 debug_backtrace 的工作原理感到困惑。它 returns 执行调用的函数,而不是将调用结果的函数。例如。如果你有:

function testit() {
    someFunc(__('something'));
}

那么 $parent[1]['function'] 将包含 testit,而不是 someFunc

我认为没有任何方法可以得到 someFunc。该函数不在堆栈中的任何位置,因为直到 after __() returns.

才会调用它