Assigning a function to a variable
The following example assigns a function to a variable and then calls the function via that variable.
It is possible to refer to variables outside of the function when using the global
statement. These variables evaluate to the value they have when the function is invoked, not when they are assigned.
gettype($f)
reveals that the
PHP type of such a function-variable is
object
.
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<title>Assinging a function to a variable</title>
</head>
<body>
<?php
$var = 'before';
$f = function($arg) {
global $var;
print("arg = $arg<br>");
print("var = $var<br>");
};
$var = 'after';
print("<code>gettype(\$f)</code> = " . gettype($f) . "<br>");
print("Going to call <code>\$f(42)</code><br>");
$f(42);
?>
</body>
</html>
Creating a closure
This example is quite similar to the previous one. The main difference is that the function
statement is combined with a use($var)
which captures the value of the variable $var
at the time when the function is assigned, not when it is called. This allows to create a closure.
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<title>Assinging a function to a variable</title>
</head>
<body>
<?php
$var = 'before';
$f = function($arg) use ($var) {
print("var = $var<br>");
};
$var = 'after';
print("Going to call <code>\$f(42)</code><br>");
$f(42);
?>
</body>
</html>