這篇文章主要介紹了PHP callback函數(shù)使用方法和注意事項(xiàng),本文講解了callback函數(shù)的一些使用技巧和避免事項(xiàng),并給出了一個(gè)使用實(shí)例,需要的朋友可以參考下
在PHP中有些諸如 call_user_function() 或 usort() 的函數(shù)接受用戶自定義的函數(shù)作為一個(gè)參數(shù)。Callback 函數(shù)不僅可以是一個(gè)簡(jiǎn)單的函數(shù),它還可以是一個(gè)對(duì)象的方法,包括靜態(tài)類的方法。
一個(gè) PHP 函數(shù)用函數(shù)名字符串來(lái)傳遞。您可以傳遞任何內(nèi)建的或者用戶自定義的函數(shù),除了 array(), echo(), empty(), eval(), exit(), isset(), list(), print() 和 unset()。
一個(gè)對(duì)象的方法以數(shù)組的形式來(lái)傳遞,數(shù)組的 0 下標(biāo)指明對(duì)象名,下標(biāo) 1 指明方法名。
對(duì)于沒(méi)有實(shí)例化為對(duì)象的靜態(tài)類,要傳遞其方法,將數(shù)組 0 下標(biāo)指明的對(duì)象名換成該類的名稱即可。
Callback 函數(shù)實(shí)例:
- <?php
- // An example callback function
- function my_callback_function() {
- echo 'hello world!';
- }
- // An example callback method
- class MyClass {
- function myCallbackMethod() {
- echo 'Hello World!';
- }
- }
- // Type 1: Simple callback
- call_user_func('my_callback_function');
- // Type 2: Static class method call
- call_user_func(array('MyClass', 'myCallbackMethod'));
- // Type 3: Object method call
- $obj = new MyClass();
- call_user_func(array($obj, 'myCallbackMethod'));
- ?>
http://www.phpe.net/manual/language.pseudo-types.php
http://cn.php.net/manual/en/language.pseudo-types.php
新聞熱點(diǎn)
疑難解答