PHP函數處理函數實例詳解


1. call_user_func和call_user_func_array: 

    以上兩個函數以不同的參數形式調用回調函數。見如下示例:  

 

<?php
class AnotherTestClass {
    public static function printMe() {
        print "This is Test2::printSelf.\n";
    }
    public function doSomething() {
        print "This is Test2::doSomething.\n";
    }
    public function doSomethingWithArgs($arg1, $arg2) {
        print 'This is Test2::doSomethingWithArgs with ($arg1 = '.$arg1.' and $arg2 = '.$arg2.").\n";
    }
}

$testObj = new AnotherTestClass();
call_user_func(array("AnotherTestClass", "printMe"));
call_user_func(array($testObj, "doSomething"));
call_user_func(array($testObj, "doSomethingWithArgs"),"hello","world");
call_user_func_array(array($testObj, "doSomethingWithArgs"),array("hello2","world2"));

 

    運行結果如下:

bogon:TestPhp$ php call_user_func_test.php 
This is Test2::printSelf.
This is Test2::doSomething.
This is Test2::doSomethingWithArgs with ($arg1 = hello and $arg2 = world).
This is Test2::doSomethingWithArgs with ($arg1 = hello2 and $arg2 = world2).

2. func_get_args、func_num_args和func_get_args: 

    這三個函數的共同特征是都很自定義函數參數相關,而且均只能在函數內使用,比較適用於可變參數的自定義函數。他們的函數原型和簡要說明如下:
int func_num_args (void) 獲取當前函數的參數數量。
array func_get_args (void) 以數組的形式返回當前函數的所有參數。
mixed func_get_arg (int $arg_num) 返回當前函數指定位置的參數,其中0表示第一個參數。

<?php
function myTest() {
    $numOfArgs = func_num_args();
    $args = func_get_args();
    print "The number of args in myTest is ".$numOfArgs."\n";
    for ($i = 0; $i < $numOfArgs; $i++) {
        print "The {$i}th arg is ".func_get_arg($i)."\n";
    }
    print "\n-------------------------------------------\n";
    foreach ($args as $key => $arg) {
        print "$arg\n";
    }
}

myTest('hello','world','123456');

    運行結果如下:

Stephens-Air:TestPhp$ php class_exist_test.php 
The number of args in myTest is 3
The 0th arg is hello
The 1th arg is world
The 2th arg is 123456

-------------------------------------------
hello
world
123456

3. function_exists和register_shutdown_function:

    函數原型和簡要說明如下:

 

bool function_exists (string $function_name) 判斷某個函數是否存在。
void register_shutdown_function (callable $callback [, mixed $parameter [, mixed $... ]]) 在腳本結束之前或者是中途調用exit時調用改注冊的函數。另外,如果注冊多個函數,那么他們將會按照注冊時的順序被依次執行,如果其中某個回調函數內部調用了exit(),那么腳本將立刻退出,剩余的回調均不會被執行。

 

<?php
function shutdown($arg1,$arg2) {
    print '$arg1 = '.$arg1.', $arg2 = '.$arg2."\n";
}

if (function_exists('shutdown')) {
    print "shutdown function exists now.\n";
}

register_shutdown_function('shutdown','Hello','World');
print "This test is executed.\n";
exit();
print "This comments cannot be output.\n";

    運行結果如下:

Stephens-Air:TestPhp$ php call_user_func_test.php 
shutdown function exists now.
This test is executed.
$arg1 = Hello, $arg2 = World


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM