How to call a php function if function name is given as string

Standard

Sometimes we require to call a function with the name given as string variable. I wanted it. Just wondering how to do that in PHP? Here are the methods:

We have one inbuilt function to solve this purpose 1.call_user_func and another way is 2. Using function name as variable.

  1. call_user_funcCall the callback given by the first parameter.

Signature:

mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )

Where first parameter is function name and rest are the comma separated values that we want to pass to the functions.

Example:

<?php
function car($model)
{
   echo "You wanted a $model car, no problem\n";
}
call_user_func('car', "Merc");
call_user_func('car', "BMW"); ?>

Result:

You wanted a Merc car, no problem
You wanted a BMW car, no problem

2. Variable Function

Another way of calling such functions is by using there name as a variable.

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

Example:

<?php
function echo($msg)
{
  echo $msg;
}
$func = "echo";
$func("Print this message for me."); ?>

Result:

Print this message for me.

Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s