-1

我想看看函数在哪里被调用。

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

我得到了这段代码(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.

(来自网络的ps相同)

我的 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
4

1 回答 1

1

你对如何debug_backtrace工作感到困惑。它返回正在执行以进行调用的函数,而不是将使用结果调用的函数。例如,如果您有:

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

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

我不认为有什么办法可以得到someFunc该函数不在堆栈上的任何位置,因为在 __()返回之前它不会被调用。

于 2015-09-12T16:05:35.783 回答