2

Having a string like

12345.find_user.find_last_name

how can i split at the charachter "." and convert it to a function-call:

find_last_name(find_user(12345));

and so on....could be of N-Elements (n-functions to run)....how do i do this effectivly, performance-wise also?

Edit, here is the solution based on your replies

thanks Gaurav for your great help. Here is my complete solution based on yours:

i protected the foreach with if(function_exists($function)){ to protect the whole thing from fatal php errors, and i added a complete example:

$mystring =  '12345.find_user.find_last_name';

convert_string_to_functions($mystring);

function convert_string_to_functions($mystring){
    $functions = explode('.', $mystring);
    $arg = array_shift($functions);
    foreach($functions as $function){
        if(function_exists($function)){
            $arg = $function($arg);
        } else {
            echo 'Function '.$function.' Not found';
        }
    }

    echo $arg;
}

function find_last_name($mystring=''){

    return $mystring.' i am function find_last_name';

}

function find_user($mystring=''){

    return $mystring.' i am function find_user';

}
2
  • 5
    Please don't do that, it is just a terrible idea Commented Jan 17, 2012 at 10:11
  • i know, it is only a special case where i can only start off with strings. Commented Jan 17, 2012 at 10:42

1 Answer 1

2
$string =  '12345.find_user.find_last_name';
$functions = explode('.', $string);
$arg = array_shift($functions);
foreach($functions as $function){
    $arg = $function($arg);
}

echo $arg;
Sign up to request clarification or add additional context in comments.

3 Comments

So, at the end of the foreach loop, $arg will be find_last_name(find_user(12345));, and just writing echo $arg; will execute that function?
in first iteration it will call find_user(12345) and store the output in $arg, because output of previous function is argument to next function. So in second iteration find_last_name function will be called with argument (result of find_user(12345)).
echo $arg; is the final output after all function call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.