PHP supports the concept of variable functions. What that means is that you can append parentheses to a variable and use it as a function call. Although not frequently used, it can be beneficial when you want to call a function dynamically based on the value stored inside of the variable. Let’s just create some examples and see that this is pretty straight forward.
We’ll start by creating two functions: _subaru() _and nissan(). The two functions will _echo _out different strings. We’ll then create a _$car _variable and assign a string to it that matches one of the function names: either _subaru _or _nissan. _To call the function, we’ll append a pair of parentheses to the $car().
<?php
// Variable Functions
function subaru() {
echo "You're getting an STi";
}
function nissan() {
echo "You're getting a Skyline";
}
$car = "subaru";
$car();
$car = "nissan";
$car();
?>
view raw
38 Variable Functions.php hosted with ❤ by GitHub
Let’s walk through this example in more detail.
#computer-science #web-development #programming #php #function