data is sent to the server, which, depending on the value of one of the array elements, needs to be transferred to different functions. In order not to fence a switch / case I want to call the function like this:

$data = array( 'table' => 1, 'sumArr' = array(.....); ); myFoo.$data['table']($data); function myFoo1($data){ } function myFoo2($data){ } ..... 

and what if the code is written in OOP? This is how it works:

 $data = $this->_myfooOne($postdata); 

But so no longer:

 $varfoo = $this->"_myfoo".$num; $data = $varfoo($postdata); 

writes

syntax error unexpected "_myfoo"

or so it will not work and the value of the table element will need to be passed as an argument to one large function already there to work?

all the same, I would like to have several independent functions to which, if anything, I can address directly ..

    2 answers 2

    To dynamically call a function by name (which you define programmatically), use call_user_func()

    in your case there will be something like

     $fname = "myFoo" . $data['table']; $result = call_user_func($fname, $data); 

    In general, of course, it would be good to check the parameters for correctness (in $data['table'] you have a valid value), and it is also possible to make sure that such a function is defined using function_exists($fname) :

     if(function_exists($fname)){ call_user_func($fname, $data); } 

    Although you can do it easier, using the "variable functions"

     $fname = "myFoo" . $data['table']; $result = $fname(); 

    if the work goes in the context of the object, then in general nothing changes

     $fname = "myFoo" . $data['table']; $result = $this->$fname($data); 

    in the case of using call_user_func , the first argument should be not just the name of the function, but an array containing the address of the object instance and the name of the function), a-la

     call_user_func([$this, $fname], $data) 
    • and what to do in a case with OOP? added a question - Yevgeny Shevtsov
    • @ EvgenyShevtsov did not read the link, right? :) added an answer - teran
    • @ EvgenyShevtsov from your example could be done like this: $varfoo = $this->{"_myfoo".$num}; - braces - Peresada
     <?php $data = array( 'table'=>1, 'sumArr' => array() ); function myFoo1($data){ print_r($data); } function myFoo2($data){ print_r($data); } $function = 'myFoo'.$data['table']; $function($data);