Home > Backend Development > PHP Tutorial > PHP code to call function through string

PHP code to call function through string

WBOY
Release: 2016-07-25 09:12:27
Original
843 people have browsed it

Learn php to call functions through strings.

1. call_user_func

  1. function a($b,$c){
  2. echo $b;
  3. echo $c;
  4. }
  5. call_user_func('a', "111","222");
  6. call_user_func('a', "333","444");
  7. //Display 111 222 333 444
  8. ?>
Copy code

It is strange to call the method inside the class, actually using array , I don’t know how the developers thought about it. Of course, new is omitted, which is also full of novelty:

  1. class a {
  2. function b($c){
  3. echo $c;
  4. }
  5. } // www.jbxue.com
  6. call_user_func(array("a", "b"),"111");
  7. //Display 111
  8. ?>
Copy code

2. call_user_func_array

The call_user_func_array function is very similar to call_user_func, except that the parameters are passed in a different way to make the structure of the parameters clearer:

  1. function a($b, $c){
  2. echo $b;
  3. echo $ c;
  4. }
  5. call_user_func_array('a', array("111", "222"));
  6. //Display 111 222
  7. ?>
Copy code

The call_user_func_array function can also be called inside the class The method of

  1. Class ClassA{
  2. function bc($b, $c) {
  3. $bc = $b + $c;
  4. echo $bc;
  5. }
  6. } // www.jbxue.com
  7. call_user_func_array(array('ClassA','bc'), array("111", "222"));
  8. //Display 333
  9. ?>
Copy code

Both the call_user_func function and the call_user_func_array function are supported quotes, which makes them more functionally consistent with ordinary function calls:

  1. function a(&$b){
  2. $b++;
  3. }
  4. $c = 0;
  5. call_user_func('a', &$ c);
  6. echo $c;//Display 1
  7. call_user_func_array('a', array(&$c));
  8. echo $c;//Display 2
Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template