PHP 函數call

來源:互聯網
上載者:User

 下面來和大家分享一下這個call_user_func_array和call_user_func函數的用法,另外附贈func_get_args()函數和func_num_args()函數,嘿嘿!! 

call_user_func函數是當需要動態調用函數時,才使用的,這個函數有兩種用法:第一種是調用孤獨的函數:  代碼如下:<?phpfunction funa($b,$c){    echo $b;    echo $c;}call_user_func('funa', "111","222");call_user_func('funa', "333","444");//顯示 111 222 333 444//大家有沒有發現,這個用法有點像javascript中的call方法,嘿嘿?>第二種是調用類內部的函數: 代碼如下:<?phpclass a {    function b()    {        $args = func_get_args();        $num = func_num_args();        print_r($args);        echo $num;    }}call_user_func(array("a", "b"),"111","222");?>上面這個例子,自己運行一下看看結果是什麼吧~嘿嘿~提示一下func_get_args()函數是擷取傳入到函數中的參數,返回一個數組,func_num_args()函數擷取傳入函數中的參數的個數。 下面再來看看call_user_func_array函數這個函數也是當需要動態調用函數時用到的,它的用法和call_user_func函數比較像,只是參數傳入的是數組。  代碼如下:<?phpfunction a($b, $c){    echo $b;    echo $c; }call_user_func_array('a', array("111", "222"));//顯示 111 222?> call_user_func_array函數也可以調用類內部的方法的 代碼如下:<?phpClass ClassA{    function bc($b, $c) {         $bc = $b + $c;        echo $bc;    } }call_user_func_array(array(‘ClassA','bc'), array(“111″, “222″));//顯示 333?> 下面再看一個動態調用函數的例子: 代碼如下:<?phpfunction otest1 ($a){     echo( '一個參數' );} function otest2 ( $a, $b){    echo( '二個參數' );} function otest3 ( $a ,$b,$c){    echo( '三個啦' );} function otest (){    $args = func_get_args();    $num = func_num_args();    call_user_func_array( 'otest'.$num, $args  );}otest("11");otest("11","22");otest("11","22","33");?> 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.