PHP函式處理函式例項詳解

OrangeAdmin發表於2014-01-08

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

相關文章