Picture

Hi, I'm Boopathi Rajaa.

Hacker, Dancer, Biker, Adventurist

Variable functions - PHP

We might have come across many programming and scripting languages - including php, but in php we might not have used this frequently or would have wanted something like this while web development. There is this ability in php to call a function whose name is a variable. So at a place in the program, different functions can be called with the same variable name(Note: Here it is not overloading - I din't tell function name).

<?php
function myFunc() {
echo "You call myfunc";
}

function myFunction($temp) {
echo "You called myfunction and provided the argument = " . $temp;
}

var $myVar = 'myFunc';
$myVar();
$myVar = $myVar . 'tion' ;
$myVar("sampleText");
?>

Here the first time $myVar() is called, the function with the name assigned to $myVar is called i.emyFunc() is called. For the second time, the value of $myVar becomes "myFunction", so now when calling $myVar() now, myFunction() is called.

Found this little concept in php very useful when working with classes and calling functions under loops. Try it and Have fun with simplicity in coding.