I have a function
function my_dump($a,$name){
echo \'\'.$name.\":\\n\";
var_export($a);
echo \'
\';
}
How can
function my_dump($a) {
$backtrace = debug_backtrace()[0];
$fh = fopen($backtrace['file'], 'r');
$line = 0;
while (++$line <= $backtrace['line']) {
$code = fgets($fh);
}
fclose($fh);
preg_match('/' . __FUNCTION__ . '\s*\((.*)\)\s*;/u', $code, $name);
echo ''.trim($name[1]).":\n";
var_export($a);
echo '
';
}
It does not run right - because used expression does not give correct result.
Using of \s* has not sense because nothing can be between name of function and brackets with parameters.
Using of ; in expression has not sense too. At least because is allows only standalone using of this function where result of this function is given to else variable. But sometimes it may be needed to use this function as parameter.
And using of (.*) will allow also all that is behind variable name given as parameter - even if there is semicolon.
So, it is needed to exclude of sign of end bracket, ), from result. There are many ways how to do that.
You can use form from code of function below or this (or something else)
'/'.__FUNCTION__.'\((\w+)\)/'
Whole function may be very simplified into (for example, this is case of class function):
protected function Get_VariableNameAsText($Variable="")
{
$File = file(debug_backtrace()[0]['file']);
for($Line = 1; $Line < count($File); $Line++)
{
if($Line == debug_backtrace()[0]['line']-1)
{
preg_match('/'.__FUNCTION__.'\(([^\)]*)\)/', $File[$Line], $VariableName);
return trim($VariableName[1]);
}
}
}
I deleted using of var_export because I don't see why to use it, when I only want to get variable name as string (text). And printing of given string is better outside of this function.
If you have not 5.4 or greater, you need to change code
$File = file(debug_backtrace()[0]['file']);
if($Line == debug_backtrace()[0]['line']-1)
on
$Trace = debug_backtrace();
$File = file($Trace[0]['file']);
if($Line == $Trace[0]['line']-1)