How to understand php callbacks
Callback function callback
We all know that when asynchronous requests are often processed in js, if you use ordinary function, 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 The value of the composite type is actually the value returned by the callback function
callable $callback The callback function can be a function name, an array, or a string
mixed $parameter The parameter of the function, Display in a sequential manner
Let’s introduce the use of demo
demo1: callback php function string form
<?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 等认为的常用函数实际上是一个操作符.并不能算函数。
Related recommendations: "PHP Getting Started Tutorial》
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 It is found that the parameters passed may not be fixed, so using 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 a little different. different.
Function call_user_func_array()
demo1: callback php function indefinite 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 Callable function
bool is_callable ( callable $name [, bool $syntax_only = false [, string &$callable_name ]] )
name
to be checked Callback.
syntax_only
If set to TRUE, this function only verifies that name may be a function or method.
callable_name
Accepts "callable name".
return
Returns TRUE if name is callable, otherwise returns 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 in js
<?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的变量,同时又不是引用对象 变量的话,则不会修改 ?>
The above is the detailed content of How to understand php callbacks. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
