zoukankan      html  css  js  c++  java
  • call_user_func

    UCenter源代码里有一个函数call_user_func,开始以为是自己定义的函数,结果到处都找不到。后来才知道call_user_func是PHP的内置函数,该函数允许用户调用直接写的函数并传入一定的参数,下面总结下这个函数的使用方法。

    call_user_func函数类似于一种特别的调用函数的方法,使用方法如下:

     
     
    <?php
    class a {   
    	function b($c)   
    	{   
    		echo $c;   
    	}   
    }   
    call_user_func(array("a", "b"),"111");   
    //显示 111   
    ?>   

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

    <?php class a { function b($c) { echo $c; } } call_user_func(array("a", "b"),"111"); //显示 111 ?>

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

     
    <?php
    function a($b, $c)   
    {   
    	echo $b;   
    	echo $c;   
    }   
    call_user_func_array('a', array("111", "222"));   
    //显示 111 222   
    ?>  

    call_user_func_array函数也可以调用类内部的方法的:

    01 <?php
    02 Class ClassA  
    03 {  
    04    
    05 function bc($b, $c) {  
    06      $bc = $b + $c;  
    07 echo $bc;  
    08 }  
    09 }  
    10 call_user_func_array(array('ClassA','bc'), array("111", "222"));  
    11    
    12 //显示 333  
    13 ?>  

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

    01 <?php
    02 function a($b)  
    03 {  
    04     $b++;  
    05 }  
    06 $c = 0;  
    07 call_user_func('a', $c);  
    08 echo $c;//显示 1  
    09 call_user_func_array('a', array($c));  
    10 echo $c;//显示 2 
    11 ?>

    另外,call_user_func函数和call_user_func_array函数都支持引用。

    01 <?php
    02 function increment(&$var)
    03 {
    04     $var++;
    05 }
    06 $a = 0;
    07 call_user_func('increment', $a);
    08 echo $a; // 0
    09 call_user_func_array('increment', array(&$a)); // You can use this instead
    10 echo $a; // 1
    11 ?>
  • 相关阅读:
    67. Add Binary
    66. Plus One
    64. Minimum Path Sum
    63. Unique Paths II
    How to skip all the wizard pages and go directly to the installation process?
    Inno Setup打包之先卸载再安装
    How to change the header background color of a QTableView
    Openstack object list 一次最多有一万个 object
    Openstack 的 Log 在 /var/log/syslog 里 【Ubuntu】
    Git 分支
  • 原文地址:https://www.cnblogs.com/killallspree/p/3306047.html
Copyright © 2011-2022 走看看