← Back to Chapters

PHP Variable Functions

? PHP Variable Functions

? Quick Overview

PHP variable functions allow a variable to hold the name of a function and call it dynamically. This enables flexible and dynamic execution of functions at runtime.

? Key Concepts

  • Function names can be stored in variables
  • Variables can dynamically invoke functions
  • Useful for callbacks and dynamic logic

? Syntax / Theory

? View Code Example
// Store function name in a variable and call it
$functionName = 'someFunction';
$functionName();

? Example 1: Basic Variable Function

Call a function dynamically using a variable:

? View Code Example
// Define a simple function
function sayHello() {
echo "Hello, World!";
}

// Assign function name to variable and call it
$func = 'sayHello';
$func();

? Example 2: Passing Arguments to Variable Functions

You can also pass arguments to functions via variable functions:

? View Code Example
// Function with parameter
function greet($name) {
echo "Hello, $name!";
}

// Call function dynamically with argument
$func = 'greet';
$func('Alice');

? Example 3: Multiple Functions

? View Code Example
// Define multiple operations
function add($a, $b) {
return $a + $b;
}

function multiply($a, $b) {
return $a * $b;
}

// Choose operation dynamically
$operation = 'multiply';
echo $operation(5, 10);

? Live Output / Explanation

The selected function name stored in a variable is executed at runtime, producing output based on the chosen logic.

? Interactive Concept

Think of variable functions like a remote control — the button you press (variable value) decides which action (function) runs.

? Use Cases

  • Callback systems
  • Routing logic
  • Plugin or hook architectures

✅ Tips & Best Practices

  • Always validate with is_callable()
  • Avoid excessive dynamic calls for readability
  • Use meaningful function names

? Try It Yourself

  • Create a calculator using variable functions
  • Use user input to select a function
  • Combine with arrays of callbacks