Web Analytics

PHP Variable Functions

Intermediate~25 min read

Variable functions and closures give you powerful ways to work with functions dynamically. Perfect for callbacks, event handlers, and functional programming!

Output
Click Run to execute your code

Variable Functions

<?php
function sayHello() {
    return "Hello!";
}

$func = 'sayHello';
echo $func();  // Calls sayHello()
?>

Anonymous Functions (Closures)

<?php
$greet = function($name) {
    return "Hello, $name!";
};

echo $greet("Alice");
?>

The use Keyword

<?php
$message = "Welcome";
$greeter = function($name) use ($message) {
    return "$message, $name!";
};

echo $greeter("Bob");
?>

Summary

  • Variable function: Call by variable name
  • Anonymous: function() { }
  • Closure: Captures variables with use
  • Callbacks: Pass functions as arguments

What's Next?

Next, learn about Arrow Functions - the modern, concise syntax in PHP 7.4+!