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.

  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.”

#computer-science #web-development #programming #php #function

PHP 7.x — P38: Variable Functions
1.45 GEEK