Home  >  Article  >  Backend Development  >  PHP callback函数使用方法和注意事项_php技巧

PHP callback函数使用方法和注意事项_php技巧

WBOY
WBOYOriginal
2016-05-16 20:25:06894browse

在PHP中有些诸如 call_user_function() 或 usort() 的函数接受用户自定义的函数作为一个参数。Callback 函数不仅可以是一个简单的函数,它还可以是一个对象的方法,包括静态类的方法。

一个 PHP 函数用函数名字符串来传递。您可以传递任何内建的或者用户自定义的函数,除了 array(), echo(), empty(), eval(), exit(), isset(), list(), print() 和 unset()。

一个对象的方法以数组的形式来传递,数组的 0 下标指明对象名,下标 1 指明方法名。

对于没有实例化为对象的静态类,要传递其方法,将数组 0 下标指明的对象名换成该类的名称即可。

Callback 函数实例:

复制代码 代码如下:

// An example callback function
function my_callback_function() {
   echo 'hello world!';
}
// An example callback method
class MyClass {
   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'));
?>

http://www.phpe.net/manual/language.pseudo-types.php
http://cn.php.net/manual/en/language.pseudo-types.php
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