Funktionen
PHP Manual

Anonymous functions

Anonyme Funktionen, auch bekannt als closures, ermöglichen es Funktionen ohne Funktionsnamen zu schreiben. Sie sind am wertvollsten als Callback callback Parameter, haben aber noch viele andere Verwendungsmöglichkeiten.

Beispiel #1 Beispiel für eine anonyme Funktion

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return 
strtoupper($match[1]);
}, 
'hello-world');
// outputs helloWorld
?>

Closures können auch als Werte von Variablen verwendet werden; PHP konvertiert solche Ausdrücke automatisch in Instanzen der internen Klasse Closure. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon:

Beispiel #2 Anonymous function variable assignment example

<?php
$greet 
= function($name)
{
    
printf("Hello %s\r\n"$name);
};

$greet('World');
$greet('PHP');
?>

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.

Beispiel #3 Inheriting variables from the parent scope

<?php
$message 
'hello';

// No "use"
$example = function () {
    
var_dump($message);
};
echo 
$example();

// Inherit $message
$example = function () use ($message) {
    
var_dump($message);
};
echo 
$example();

// Inherited variable's value is from when the function
// is defined, not when called
$message 'world';
echo 
$example();

// Reset message
$message 'hello';

// Inherit by-reference
$example = function () use (&$message) {
    
var_dump($message);
};
echo 
$example();

// The changed value in the parent scope
// is reflected inside the function call
$message 'world';
echo 
$example();

// Closures can also accept regular arguments
$example = function ($arg) use ($message) {
    
var_dump($arg ' ' $message);
};
$example("hello");
?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

Notice: Undefined variable: message in /example.php on line 6
NULL
string(5) "hello"
string(5) "hello"
string(5) "hello"
string(5) "world"
string(11) "hello world"

Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example:

Beispiel #4 Closures and scoping

<?php
// A basic shopping cart which contains a list of added products
// and the quantity of each product. Includes a method which
// calculates the total price of the items in the cart using a
// closure as a callback.
class Cart
{
    const 
PRICE_BUTTER  1.00;
    const 
PRICE_MILK    3.00;
    const 
PRICE_EGGS    6.95;

    protected 
$products = array();
    
    public function 
add($product$quantity)
    {
        
$this->products[$product] = $quantity;
    }
    
    public function 
getQuantity($product)
    {
        return isset(
$this->products[$product]) ? $this->products[$product] :
               
FALSE;
    }
    
    public function 
getTotal($tax)
    {
        
$total 0.00;
        
        
$callback =
            function (
$quantity$product) use ($tax, &$total)
            {
                
$pricePerItem constant(__CLASS__ "::PRICE_" .
                    
strtoupper($product));
                
$total += ($pricePerItem $quantity) * ($tax 1.0);
            };
        
        
array_walk($this->products$callback);
        return 
round($total2);
    }
}

$my_cart = new Cart;

// Add some items to the cart
$my_cart->add('butter'1);
$my_cart->add('milk'3);
$my_cart->add('eggs'6);

// Print the total with a 5% sales tax.
print $my_cart->getTotal(0.05) . "\n";
// The result is 54.29
?>

Anonymous functions are implemented using the Closure class.

Changelog

Version Beschreibung
5.4.0 $this can be used in anonymous functions.
5.3.0 Anonymous functions become available.

Anmerkungen

Hinweis: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within a closure.


Funktionen
PHP Manual