Funktionen
PHP Manual

Variablenfunktionen

PHP unterstützt das Konzept der Variablenfunktionen. Wenn Sie an das Ende einer Variablen Klammern hängen, versucht PHP eine Funktion aufzurufen, deren Name der aktuelle Wert der Variablen ist. Dies kann unter anderem für Callbacks, Funktionstabellen, usw. genutzt werden.

Variablenfunktionen funktionieren nicht mit Sprachkonstrukten wie echo, print, unset(), isset(), empty(), include und require. Sie müssen Ihre eigenen Wrapperfunktionen verwenden, um diese Konstrukte als variable Funktionen benutzen zu können.

Beispiel #1 Beispiel für Variablenfunktionen

<?php
function foo()
{
    echo 
"In foo()<br />\n";
}

function 
bar($arg '')
{
    echo 
"In bar(); der Parameter ist '$arg'.<br />\n";
}

// Dies ist eine Wrapperfunkiton für echo
function echoit($string)
{
    echo 
$string;
}

$func 'foo';
$func();        // Dies ruft foo() auf

$func 'bar';
$func('test');  // Dies ruft bar() auf

$func 'echoit';
$func('test');  // Dies ruft echoit() auf
?>

Sie können auch die Methode eines Objektes mittels der variablen Funktionen aufrufen.

Beispiel #2 Variable Methode

<?php
class Foo
{
    function 
Variable()
    {
        
$name 'Bar';
        
$this->$name(); // Dies ruft die Bar() Methode auf
    
}

    function 
Bar()
    {
        echo 
"Das ist Bar";
    }
}

$foo = new Foo();
$funcname "Variable";
$foo->$funcname();   // Dies ruft $foo->Variable() auf

?>

When calling static methods, the function call is stronger than the static property operator:

Beispiel #3 Variable method example with static properties

<?php
class Foo
{
    static 
$variable 'static property';
    static function 
Variable()
    {
        echo 
'Method Variable called';
    }
}

echo 
Foo::$variable// This prints 'static property'. It does need a $variable in this scope.
$variable "Variable";
Foo::$variable();  // This calls $foo->Variable() reading $variable in this scope.

?>

As of PHP 5.4.0, you can call any callable stored in a variable.

Beispiel #4 Complex callables

class Foo
{
    static function bar()
    {
        echo "bar\n";
    }
    function baz()
    {
        echo "baz\n";
    }
}

$func = array("Foo", "bar");
$func(); // prints "bar"
$f = array(new Foo, "baz");
$func(); // prints "baz"
$f = "Foo::bar";
$func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error

Siehe auch is_callable(), call_user_func(), Variable Variablen und function_exists().

Changelog

Version Beschreibung
7.0.0 'ClassName::methodName' is allowed as variable function.
5.4.0 Arrays, which are valid callables, are allowed as variable functions.


Funktionen
PHP Manual