Friday, October 23, 2009

PHP User Defined Functions Specialties

Each and every language has its on specialties. Here I listing the some useful features of PHP user defined functions.

Conditional Functions

We can define a function with in a condition. Function will only execute if condition satisfies.

E.g.:

$flag = true;

if($flag)
{
function insideCondition()
{
echo “
am inside“;
}
}

insideCondition();

if flag is true you will get following output

am inside

else

Fatal error: Call to undefined function insideCondition()

Function inside a Function

PHP allows you to declare a function inside a function. You can execute the inner function after calling the container function.

E.g.:

function parentFun()
{
echo "From Parent
";
function childFun()
{
echo "From Child
";
}
}

parentFun();

childFun();

Output will be

From Parent
From Child

If you call childFun() before parentFun(), you will get function undefined error.

Variable Function

PHP supports us to assign a function to a variable. After that we can use that variable as function, it allows us to pass function arguments also.

E.g.:

function newFun($str)
{
echo $str;
}

$varFun = ‘newFun’;

$var = "Hi Friends";

$varFun($var);