search
HomeBackend DevelopmentPHP Tutorial Make code sweet.PHP非一般用法的一些总结(2)-PHP中的‘callback’回调

Make code sweet.PHP特殊用法的一些总结(2)--PHP中的‘callback’回调
本章总结一下PHP中‘callback’的一些实用用法。

1. 什么是callback?
    首先简单的介绍一下‘callback’,俗称‘回调’,是一种将一段可执行代码作为参数传递以供另一个函数调用的行为,回调在不同语言有不同的实现方式,几乎现在所有的主流语言都支持这个特性,我总结实现callback的主要方式有两种:
1.以C++、C#等静态语言为主的通过函数指针方式实现回调
2.以Ruby、JavaScript等动态语言为主的通过lambda表达式(也叫匿名函数)实现回调
关于‘callback’的详细定义可以参看维基百科:http://en.wikipedia.org/wiki/Callback_(computer_programming),

2.PHP中复杂的callback
    说起callback,很多人马上回想起PHP 5.3的lambda函数实现方式,这个的确是实现callback最方便最养眼的一种方法,如果你有机会使用PHP 5.3,一定要狠狠的使用它。但是对于那些无法使用PHP 5.3或者必须兼容低版本的应用而言,其实PHP中还是有很多其他的callback实现方式,下面我们一一道来。

  • PHP支持函数指针的方式实现,实现规则如下:
  • 如果传一个函数,将函数名以字符串形式传给参数
    如果传一个对象的方法,将一个数组传给参数,其中index=0的位置放对象,index=1的位置放方法名字符串
    如果传一个类的静态方法,将一个数组传给参数,其中index=0的位置放类名字符串,index=1的位置放方法名字符串

  • PHP支持使用函数create_function创建匿名函数
  • 这个是PHP 5.3以下版本创建匿名函数的唯一方式,原型如下:
    string create_function ( string $args , string $code )
    

      不过这个函数中把函数的参数列表和实现都放到了字符串中,在编辑器中无法语法高亮,很容易出错,而且还要对代码中的字符进行转义,这些复杂性限制了PHP中匿名函数的使用。

  • 就是前面提到的使用lambda函数(仅PHP 5.3及以上版本支持)
  •     随着闭包、lambda函数在语言中的流行,PHP也支持了lambda函数,语法仿照了javascript的匿名函数,不过和Ruby、JavaScript的闭包不同的是它不能访问闭包外层的变量,除非使用use将变量显示的引入。

        在PHP标准库中,如:array_map,usort等函数支持传递callback参数,你可以用上述任意方式作为参数。这样已经足够了,想实现一个函数,用户可以传递callback参数?当然没有问题,在参数列表中有一个callback参数,写着函数的实现,突然顿了顿,然后问出了如下问题:

    3.如何在函数中调用callback
        是啊,上面提到了如何构建callback参数,那如何在函数中执行这个参数呢?最容易想到的方式是直接使用字符串变量来执行函数,比如:
    $a='FunctionName';
    $a();
    

        这种方式直观,简单。不过这个方法不是对所有的callback形式的参数都有效,如果想兼容所有的callback参数,可以使用以下的函数:

    call_user_func和call_user_func_array
        这两个函数的用途是一样的,区别是call_user_func_array的函数传递给callback函数的参数必须用array排列,使用哪个凭个人喜好,我倾向使用call_user_func,字符少,参数更灵活。函数的原型如下:
    mixed call_user_func ( callback $function [, mixed $parameter [, mixed $... ]] )
    mixed call_user_func_array ( callback $function , array $param_arr )
    

    为了提高函数的容错性,我们需要在调用之前判断参数是否可以调用,这是可以使用如下函数:

    is_callable
    函数原型如下:
    bool is_callable ( callback $name [, bool $syntax_only= false [, string &$callable_name ]] )
    


      关于PHP中的callback就总结到这里。我的微博地址:http://weibo.com/jameren,欢迎大家关注, Make code sweet.PHP非一般用法的一些总结(2)-PHP中的‘callback’回调   。
    顺便做个广告:
    引用

    我最近使用了15G超大空间免费网络U盘―@酷盘,可在PC及手机上使用,无文件类型及大小限制,传输速度快,文件永不丢失,一起来体验吧!通过下面的邀请链接注册,你和我都将额外获得256MB的酷盘空间! http://t.cn/aNLZje
    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

    What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

    PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

    PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

    PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

    PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

    PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

    PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

    Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

    PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

    PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

    PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

    PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

    PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

    How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

    PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft