2016-04-13 10 views
0

In JavaScript können Sie etwas tun:Aufrufen von Methoden und Verschlüsse aus einem Array

var Module = (function() { 
    var functions = [method1, method2]; // array of functions to execute 

    function method1() { 
     console.log('calling method1'); 
    } 

    function method2() { 
     console.log('calling method2'); 
    } 

    function method3() { 
     console.log('calling method3'); // not called 
    } 

    function add (fn) { 
     functions.push(fn); // add new function to the array 
    } 

    function printt() { 
     for (var i in functions) functions[i](); // execute functions in the array 
    } 

    return { 
     add: add, 
     printt: printt 
    }; 
})(); 

Module.add(function() { 
    console.log('calling anonymous function'); 
}); 

Module.printt(); 

// calling method1 
// calling method2 
// calling anonymous function 

Ist es möglich, etwas ähnliches in PHP zu tun, wo (1) Methoden werden in einem Array gespeichert sind, auszuführen (2) und neue Funktionen/Methoden können zum Array hinzugefügt werden, so dass, wenn die printt Methode ausgeführt wird, führt es alle Funktionen im Array aus?

class Module { 
    protected $functions = []; 

    public function __construct() { 
     // ? 
    } 

    protected function method1() { 
     echo 'calling method1'; 
    } 

    protected function method2() { 
     echo 'calling method2'; 
    } 

    protected function method3() { 
     echo 'calling method3'; 
    } 

    public function add ($fn) { 
     $this->functions[] = $fn; 
    } 

    public function printt() { 
     foreach ($this->functions as $fn) $fn(); 
    } 
} 

$module = new Module(); 

$module->add(function() { 
    echo 'calling anonymous function'; 
}); 

$module->printt(); 
+0

Hat PHP sogar Verschlüsse? – evolutionxbox

+0

Ich glaube so nach dieser Seite [Anonymous Funktionen] (http://php.net/manual/en/functions.anonymous.php). – Mikey

+0

wow. Ich wusste es nicht. Nizza – evolutionxbox

Antwort

2

prüfen is_callable() für Verschlüsse und method_exists() für die Methoden des Objekts.

Es gibt auch einen Unterschied zu JS, dass Sie die Methode korrekt referenzieren müssen - mit $ this innerhalb des Objekts.

+0

Das ist, was ich zunächst dachte. "Vielleicht gibt es einen anderen Weg?" Schätze nicht. Vielen Dank. – Mikey

1

Eine andere Möglichkeit ist das Hinzufügen der Member-Methoden zum Funktions-Array als Callables und nicht nur als Methodennamen und dann die Ausführung mit call_user_func.

class Module { 
    public function __construct() { 
    $this->functions = [ 
     [$this, 'method1'], 
     [$this, 'method2'], 
    ]; 
    } 

    // ... 

    public function printt() { 
    foreach($this->functions as $fn) { 
     call_user_func($fn); 
    } 
    } 
} 
Verwandte Themen