It is easier to understand it as a variable, such as $a=function(){echo "aaa";};$aa(); or function a(){}; assign the function name as a variable; $b ="a"; $b(); One is anonymous function to be called as a variable, and the other is the function name to be called as a variable. This is the common way of callback function, simple For example, this way of calling a function is called a callback function
Callback function callback
We all know that when asynchronous requests are often processed in js, if an ordinary function is used , may not be guaranteed to be called after the asynchronous request is completed. So there is a callback function, especially during file processing and ajax processing, the callback function is very useful.
Function call_user_func()
mixed call_user_func (callable $callback [, mixed $parameter [, mixed $... ]] )
return returns a composite type value, which is actually returned by the callback function Value
callable $callback The callback function can be a function name, an array, or a string
mixed $parameter The parameters of the function are displayed in sequence
Let’s introduce the use of demo
demo1: Callback php function string format
<?php $data = array("name"=>"callback" , "value"=>"test"); $rs1 = http_build_query($data); //直接调用php函数 $rs2 = call_user_func("http_build_query",$data); //使用回调函数 echo $rs1; //name=callback&value=test echo "<br />"; echo $rs2; //name=callback&value=test // 这里需要注意的是,参数1必须是可使用的函数可以通过function_exists()返回true的函数,这里提醒isset,empty,is_null 等认为的常用函数实际上是一个操作符.并不能算函数。
demo2 Callback php function function name variable format
<?php //自定义函数 function myUrldecode($str){ return urldecode($str); } $data = array("name"=>"callback" , "value"=>"天才"); $str = http_build_query($data); $rs1 = urldecode($str); //urlencode编码 $rs2 = call_user_func(myUrldecode,$str); echo $rs1; //name=callback&value=天才 echo "<br />"; echo $rs2; //name=callback&value=天才 //这里我们可以看到,我们直接使用函数的名称也是可以的,不需要带引号字符串。 ?>
demo3 Callback class method array format
<?php class MyClass{ private $demo = "test"; function myUrldecode($str){ return urldecode($str); } static function myUrlencode($str){ return urlencode($str) ; } } $str = "?query=/test/demo1"; $encode = call_user_func(array(MyClass,"myUrlencode"),$str); //直接使用类的静态方法 将字符串进行url编码 不再是字符串或者函数名,而是一个数组格式,第一个项表示类名,第二个项则表示方法名。 第一项可以为类的引用地址,第二项为静态方法名称 $decode = call_user_func(array("MyClass","myUrlencode"),$encode); //同样是使用类的方法,不过调用的是普通方法名称。 echo $encode; //%3Fquery%3D%2Ftest%2Fdemo1 echo "<br />"; //?query=/test/demo1 echo $decode; //注意 使用方法名也具有作用域的概念,即private protected 和 public,通常回调类方法都只能调用publi 和默认作用域的 方法。 //同时如果是普通方法,并且内部使用了$this变量,那么进行调用是无法成功的. ?>
demo4 Callback class method string format
<?php class MyClass{ private $demo = "test"; function myUrldecode($str){ return urldecode($str); } private function myUrldecode2($str){ return urldecode($str); } static function myUrlencode($str){ return urlencode($str) ; } } $str = "?query=/test/demo1"; $encode = call_user_func("MyClass::myUrlencode",$str); $decode = call_user_func("MyClass::myUrldecode",$encode); echo $encode; // %3Fquery%3D%2Ftest%2Fdemo1 echo "<br />"; echo $decode; // ?query=/test/demo1 $encode2 = call_user_func("MyClass::myUrlencode2",$str); var_dump($encode2); // null //如果直接使用字符串的方法的话,那么必须在类和方法名中添加::作为分割。 //这里我们发现不是静态方法也可以用::进行调用 //这里进行了一个测试,发现调用private 作用域的方法返回的是一个null值,说明确实存在作用域的关系 ?>
demo5 Callback object method array format
<?php class MyClass{ private $demo = "test"; function myUrldecode($str){ return urldecode($str) ."-" .$this->demo ; //调用内部的this作用域 } static function myUrlencode($str){ return urlencode($str); } } $str = "?query=/test/demo1"; $class = new MyClass(); $encode = call_user_func(array($class,"myUrlencode"),$str); $decode = call_user_func(array($class,"myUrldecode"),$str); echo $encode; //%3Fquery%3D%2Ftest%2Fdemo1 echo "<br />"; echo $decode; //?query=/test/demo1-test //很明显,如果使用对象做为回调函数,内部的private 属性和方法也可以使用,但是对外的方法必须为默认或者 public类型 //对象数组方式第一个选项必须为一个对象 ?>
Sometimes we find that the parameters passed may not be fixed, then use call_user_func () will cause some trouble. At this time, you can use the call_user_func_array() method. Most of the usage methods are the same, but the use of parameters will be slightly different.
Function call_user_func_array()
demo1 Callback php function with variable parameters
<?php $record1 = array( 'id' => 2135, ); $record2 = array( 'first_name' => 'Sally', ); $record3 = array( 'last_name' => 'Jones', ); $return = array_merge($record1,$record2,$record3); //如果使用回调函数,则如下 $return = call_user_func_array("array_merge", array($record1,$record2,$record3)); print_r($return); //Array ( [id] => 2135 [first_name] => Sally [last_name] => Jones ) //一些特别的函数允许你有不固定的参数,如果你还将它作为回调函数,则可以使用这个方法进行调用. ?>
tips1 How to determine whether it is a callback function
bool is_callable (callable $name [, bool $syntax_only = false [, string &$callable_name ]] )
name
The callback function to be checked.
syntax_only
If set to TRUE, this function only verifies that name may be a function or method.
callable_name
Accepts "callable name".
return
If name is callable, return TRUE, otherwise return FALSE
<?php // is_callable(); $bool = is_callable(urlencode); // true $bool = is_callable(urlencode,false); // true $bool = is_callable(urlencode,true); // true $bool = is_callable("urlencode",false,$callable_name1); // string urlencode $bool = is_callable("urldecode",true,$callable_name2); // string urldecode 即使不存在回调函数也会返回true ?>
tips2 Get the parameters of the function, similar to arguments
<?php //这里指的是非客户端php脚本 function sum($first,$second){ $args = func_get_args(); //获取列表 //func_get_arg($index) 则获取指定的位置的参数 $len = func_num_args(); //获取长度 $sum = 0 ; foreach($args as $key=>$val){ $sum += (int) $val; } return $sum; } $rs = sum(1,2,3,4,5); var_dump($rs); // int 15 //注意: 在sum函数中修改了$first,$second的变量,同时又不是引用对象 变量的话,则不会修改 ?>in js
The above is the detailed content of What is the use of php callback function?. For more information, please follow other related articles on the PHP Chinese website!

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 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 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 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.

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 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.

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

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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.

Atom editor mac version download
The most popular open source editor