zoukankan      html  css  js  c++  java
  • Callbacks

    Example #1 Callback function examples

    <?php

      //An example callback function

      function my_callback_function(){

      echo 'hello world!';

    }

    class MyClass{

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

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

      }

    }

    class B extends A{

      public static function who(){

        echo "B ";

      }

    }

    call_user_func(array('B','parent::who'));

    ?>

    Example #2 Callback example using a 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:In PHP 4,it was necessary to use a reference to create a callback that points

    to the actual object,and not a copy of it.

    Note:

    在函数中注册有多个回调内容时(如使用call_user_func()与call_user_func_array()),如在前一个回调中有未捕获的异常,其后的将不再被调用。

  • 相关阅读:
    爬虫介绍
    HTTP请求协议
    谷歌浏览器表单提交,input填充背景
    SVN与GIT基础知识学习
    vue 开发环境搭建
    正则表达式验证
    canvas基础
    数组基础方法应用
    AJAX基础学习
    css弹性布局 --flex布局。
  • 原文地址:https://www.cnblogs.com/vegas/p/5217244.html
Copyright © 2011-2022 走看看