PHP函數處理函數實例詳解

1. call_user_func和call_user_func_array: php

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

 

<?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: spa

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

<?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');

    運行結果以下:blog

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:get

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

 

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";

    運行結果以下:string

Stephens-Air:TestPhp$ php call_user_func_test.php 
shutdown function exists now.
This test is executed.
$arg1 = Hello, $arg2 = World
相關文章
相關標籤/搜索