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();
Hat PHP sogar Verschlüsse? – evolutionxbox
Ich glaube so nach dieser Seite [Anonymous Funktionen] (http://php.net/manual/en/functions.anonymous.php). – Mikey
wow. Ich wusste es nicht. Nizza – evolutionxbox