首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

call_user_func

(PHP 4, PHP 5, PHP 7)

call_user_func - 调用第一个参数给出的回调

描述

代码语言:javascript
复制
mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )

callback通过第一个参数调用给定值,并将其余参数作为参数传递。

参数

callback

可调用的被调用。

parameter

要传递给回调的零个或多个参数。

注意:请注意,call_user_func()的参数不是通过引用传递的。 Example #1 call_user_func() example and references <?php error\_reporting(E\_ALL); function increment(&$var) {     $var++; } $a = 0; call\_user\_func('increment', $a); echo $a."\n"; // You can use this instead call\_user\_func\_array('increment', array(&$a)); echo $a."\n"; ?> The above example will output: 0 1

返回值

返回回调的返回值。

Changelog

版本

描述

5.3.0

像父母和自我这样的面向对象关键字的解释已经改变。以前,使用双冒号语法调用它们会发出E_STRICT警告,因为它们被解释为静态。

示例

Example #2 call_user_func() example

代码语言:javascript
复制
<?php
function barber($type)
{
    echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>

上面的例子将输出:

代码语言:javascript
复制
You wanted a mushroom haircut, no problem
You wanted a shave haircut, no problem

Example #3 call_user_func() using namespace name

代码语言:javascript
复制
<?php

namespace Foobar;

class Foo {
    static public function test() {
        print "Hello world!\n";
    }
}

call_user_func(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0
call_user_func(array(__NAMESPACE__ .'\Foo', 'test')); // As of PHP 5.3.0

?>

上面的例子将输出:

代码语言:javascript
复制
Hello world!
Hello world!

Example #4 Using a class method with call_user_func()

代码语言:javascript
复制
<?php

class myclass {
    static function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // As of 5.2.3

$myobject = new myclass();

call_user_func(array($myobject, 'say_hello'));

?>

上面的例子将输出:

代码语言:javascript
复制
Hello!
Hello!
Hello!

Example #5 Using lambda function with call_user_func()

代码语言:javascript
复制
<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'test'); /* As of PHP 5.3.0 */
?>

上面的例子将输出:

代码语言:javascript
复制
[test]

笔记

注意:如果在以前的回调中存在未捕获的异常,则不会调用使用call_user_func()和call_user_func_array()等函数注册的回调函数。

See Also

  • call_user_func_array() - 用参数数组调用回调
  • is_callable() - 验证变量的内容可以作为函数调用
  • information about the callback type
  • ReflectionFunction::invoke() - Invokes function
  • ReflectionMethod::invoke() - Invoke

← call_user_func_array

create_function →

扫码关注腾讯云开发者

领取腾讯云代金券