C'è un modo per invocare dinamicamente un metodo nella stessa classe per PHP? Non ho la sintassi corretta, ma sto cercando di fare qualcosa di simile a questo:
$this->{$methodName}($arg1, $arg2, $arg3);
C'è un modo per invocare dinamicamente un metodo nella stessa classe per PHP? Non ho la sintassi corretta, ma sto cercando di fare qualcosa di simile a questo:
$this->{$methodName}($arg1, $arg2, $arg3);
Risposte:
C'è più di un modo per farlo:
$this->{$methodName}($arg1, $arg2, $arg3);
$this->$methodName($arg1, $arg2, $arg3);
call_user_func_array(array($this, $methodName), array($arg1, $arg2, $arg3));
Puoi anche usare l'api di riflessione http://php.net/manual/en/class.reflection.php
call_user_func_arrayè quella che fa per te.
call_user_func_array($this->$name, ...)e mi chiedevo perché non avrebbe funzionato!
Basta omettere le parentesi graffe:
$this->$methodName($arg1, $arg2, $arg3);
Puoi usare l'overloading in PHP: Overloading
class Test {
private $name;
public function __call($name, $arguments) {
echo 'Method Name:' . $name . ' Arguments:' . implode(',', $arguments);
//do a get
if (preg_match('/^get_(.+)/', $name, $matches)) {
$var_name = $matches[1];
return $this->$var_name ? $this->$var_name : $arguments[0];
}
//do a set
if (preg_match('/^set_(.+)/', $name, $matches)) {
$var_name = $matches[1];
$this->$var_name = $arguments[0];
}
}
}
$obj = new Test();
$obj->set_name('Any String'); //Echo:Method Name: set_name Arguments:Any String
echo $obj->get_name();//Echo:Method Name: get_name Arguments:
//return: Any String
Puoi anche usare call_user_func()ecall_user_func_array()
Se stai lavorando all'interno di una classe in PHP, ti consiglio di utilizzare la funzione __call in sovraccarico in PHP5. Puoi trovare il riferimento qui .
Fondamentalmente __call fa per le funzioni dinamiche quello che __set e __get fanno per le variabili in OO PHP5.
Ancora valido dopo tutti questi anni! Assicurati di tagliare $ methodName se si tratta di contenuto definito dall'utente. Non sono riuscito a far funzionare $ this -> $ methodName finché non ho notato che aveva uno spazio iniziale.
È possibile memorizzare un metodo in una singola variabile utilizzando una chiusura:
class test{
function echo_this($text){
echo $text;
}
function get_method($method){
$object = $this;
return function() use($object, $method){
$args = func_get_args();
return call_user_func_array(array($object, $method), $args);
};
}
}
$test = new test();
$echo = $test->get_method('echo_this');
$echo('Hello'); //Output is "Hello"
EDIT: ho modificato il codice e ora è compatibile con PHP 5.3. Un altro esempio qui