Friday, August 14, 2009

Getting function name in a function

I came to this time when I was doing recursive functions. I thought that if I change the function name, I will have to change the name again in the codes within the function. Consider the function below.

<?php

function a($v){
$ret = array();
if(is_array($v))
{
foreach($v as $k){
$ret[] = a($k);
}
}else{
$ret = $v;
}
return $ret;
}

?>


If i were to change the function name, and I forgot to change the one within the code, I will cause myself an error and debug intensively.

However using backtrace, I am able to get the function name when inside a function. The function below enables you to get the function name when called.

<?php

function func_name(){
$bt = debug_backtrace();
$ret = '';
if(isset($bt[1]) && isset($bt[1]['function'])){
$ret = $bt[1]['function'];
}
return $ret;
}

?>


So to get the first function working even after changing function name:

<?php

function a($v){
$ret = array();
if(is_array($v))
{
$f = func_name();
foreach($v as $k){
$ret[] = $f($k);
}
}else{
$ret = $v;
}
return $ret;
}

?>


And there you have it!

This function was extracted from the php class (/class/php.class.php) of the fast and lightweight PHP framework - Samstyle PHP Framework 1.2.9 Alpha

No comments: