php回調類型(callback)

來源:互聯網
上載者:User
自 PHP 5.4 起可用 callable 類型指定回調類型 callback。本文檔基於同樣理由使用 callback 類型資訊。

一些函數如 call_user_func() 或 usort() 可以接受使用者自訂的回呼函數作為參數。回呼函數不止可以是簡單函數,還可以是對象的方法,包括靜態類方法。

傳遞

一個 PHP 的函數以 string 類型傳遞其名稱。可以使用任何內建或使用者自訂函數,但除了語言結構例如: array(), echo, empty(), eval(), exit(), isset(), list(), print 或 unset()。

一個已執行個體化的對象的方法被作為數組傳遞,下標 0 包含該對象,下標 1 包含方法名。

靜態類方法也可不經執行個體化該類的對象而傳遞,只要在下標 0 中包含類名而不是對象。自 PHP 5.2.3 起,也可以傳遞 'ClassName::methodName'。

除了普通的使用者自訂函數外, create_function() 可以用來建立一個匿名回呼函數。自 PHP 5.3.0 起也可傳遞 closure 給回調參數。

Example #1 回呼函數樣本

<?php // An example callback functionfunction my_callback_function() {   echo 'hello world!';} // An example callback methodclass MyClass {   static function myCallbackMethod() {       echo 'Hello World!';   }} // Type 1: Simple callbackcall_user_func('my_callback_function'); // Type 2: Static class method callcall_user_func(array('MyClass', 'myCallbackMethod')); // Type 3: Object method call$obj = new MyClass();call_user_func(array($obj, 'myCallbackMethod')); // Type 4: Static class method call (As of PHP 5.2.3)call_user_func('MyClass::myCallbackMethod'); // Type 5: Relative static class method call (As of PHP 5.3.0)class A {   public static function who() {       echo "A\n";   }} class B extends A {   public static function who() {       echo "B\n";   }} call_user_func(array('B', 'parent::who')); // A?>

Example #2 使用 Closure 的樣本

<?php// Our closure$double = function($a) {   return $a * 2;}; // This is our range of numbers$numbers = range(1, 5); // Use the closure as a callback here to// double the size of each element in our// range$new_numbers = array_map($double, $numbers); print implode(' ', $new_numbers);?>

以上常式會輸出:

2 4 6 8 10

Note: 在 PHP 4 中,需要使用一個引用來建立一個指向具體對象的回呼函數,而不是一個拷貝。參見引用的解釋。

Note:

在函數中註冊有多個回調內容時(如使用 call_user_func() 與 call_user_func_array()),如在前一個回調中有未捕獲的異常,其後的將不再被調用。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.