PHP Variable Functions

Adapting and Performing with Variable Functions

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();

?>

Let’s walk through this example in more detail.

  1. PHP sees the declarations for both the subaru() and the nissan() functions.
  2. On line 12, the value subaru is assigned to the variable $car.
  3. On line 13, a pair of parentheses are appended to the $car variable. PHP sees this and replaces $car() with subaru().
  4. This calls the subaru() function, which echoes out “You’re getting an STi.”
  5. PHP moves to line 15 and assigns nissan to the $car variable.
  6. On line 16, a pair of parentheses are appended to the $car variable. PHP sees this and replaces $car() with nissan().
  7. This calls the nissan() function, which echoes out “You’re getting a Skyline.”

Although this is a straightforward concept, it shouldn’t be used often since it will lead to code that’s difficult to read and in certain scenarios it can also lead to security issues, which is beyond the scope of this article.

PHP Tutorial Series

Continue your learning with these articles

PHP Functions Returning Values

NAVIGATING CODE WATERS FOR TREASURED RETURNS

PHP – P37: FUNCTIONS RETURNING VALUES

Functions can return values: there I said it. When we looked at functions previously, those functions just echoed some string. Although that is one use of a function, functions are more powerful than simply echoing out statements. We can use functions to do something and then return a calculated value to us.

PHP Variable Functions

Adapting and Performing with Variable Functions

PHP – P38: Variable functions

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.

Leave a Reply