function functionName(if clause here) possible?

By : Vidar
function getTemplate($tpl if ($vars) echo ", $vars";)...function

Is this possible somehow? The above wont work.


By : Vidar



getTemplate($tpl, ($vars)?$vars:null); // not sure

getTemplate($tpl, (!empty($vars))?$vars:null);

Also, if you would like a technique similar to echo:

$code = "getTemplate($pl";
if ( $vars ) { $code = $code . ", $vars);"; }
else { $code = $code . ");"; }
$ret = eval($code);

Although this is usually considered bad practice (never say never). Please note that all code sent to eval will be executed directly. So don't put user input in an eval() call.

Optional arguments with default values

It looks like you want an optional argument, which you can accomplish by defining a default value in the function definition:

function getTemplate($tpl, $vars=null)   


You can call this function as getTemplate($foo) or getTemplate($foo,$bar). See the PHP manual page on function arguments for more details.

Variable numbers of arguments

It's also possible to write functions which take a variable number of arguments, but you need to use func_num_args, func_get_arg and func_get_args functions to get at them. Here's an example from the manual

function foo() 
   $numargs = func_num_args();
   echo "Number of arguments: $numargs<br />\n";
   if ($numargs >= 2) {
       echo "Second argument is: " . func_get_arg(1) . "<br />\n";
   $arg_list = func_get_args();
   for ($i = 0; $i < $numargs; $i++) {
       echo "Argument $i is: " . $arg_list[$i] . "<br />\n";

foo(1, 2, 3);

Calling a function with a variable number of parameters

To round off this answer even more, suppose you'd build an array of 1..n values and wanted to pass it to the foo() function defined above? You'd use call_user_func_array

call_user_func_array('foo', $values);

This is the equivalent of calling


What's so bad about

function getTemplate($tpl, $vars=null)   {}


By : user32459

This video can help you solving your question :)
By: admin