php通过字符串调用函数示例_php实例

WBOY
Release: 2016-05-17 08:48:36
Original
910 people have browsed it

1. call_user_func

复制代码 代码如下:

function a($b,$c){
  echo $b;
  echo $c;
}
call_user_func('a', "111","222");
call_user_func('a', "333","444");

//显示 111 222 333 444
?>
 

调用类内部的方法比较奇怪,居然用的是array,不知道开发者是如何考虑的,当然省去了new,也是满有新意的:

复制代码 代码如下:

class a {
  function b($c){
    echo $c;
  }
}
call_user_func(array("a", "b"),"111");

//显示 111
?>

2. call_user_func_array

call_user_func_array函数和call_user_func很相似,只不过是换了一种方式传递了参数,让参数的结构更清晰:

复制代码 代码如下:

function a($b, $c){
  echo $b;
  echo $c;
}
call_user_func_array('a', array("111", "222"));

//显示 111 222
?>


call_user_func_array函数也可以调用类内部的方法的
 
复制代码 代码如下:

Class ClassA{
  function bc($b, $c) {
      $bc = $b + $c;
    echo $bc;
  }
}
call_user_func_array(array('ClassA','bc'), array("111", "222"));

//显示 333
?>

call_user_func函数和call_user_func_array函数都支持引用,这让他们和普通的函数调用更趋于功能一致:

复制代码 代码如下:

function a(&$b){
  $b++;
}
$c = 0;
call_user_func('a', &$c);
echo $c;//显示 1
call_user_func_array('a', array(&$c));
echo $c;//显示 2
Related labels:
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