I want to look where the function is called.
Is the function called inside a echo or sprintf? Then return, otherwise echo the content.
I got this code (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')));
?>
When I type it at the terminal all I get is:
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. from web the same)
My PHP version is:
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
You're confused about how debug_backtrace
works. It returns the functions that were executing to make the call, not the function that will be called with the result. E.g. if you have:
function testit() {
someFunc(__('something'));
}
then $parent[1]['function']
will contain testit
, not someFunc
.
I don't think there's any way to get someFunc
. That function isn't anywhere on the stack, because it doesn't get called until after __()
returns.