美文网首页PHP经验分享
PHP函数-call_user_func和call_user_f

PHP函数-call_user_func和call_user_f

作者: PHP的艺术编程 | 来源:发表于2018-12-05 14:32 被阅读15次

1. call_user_func_array

call_user_func_array文档说明

2. call_user_func

call_user_func文挡说明

说明
1. call_user_func_array的第二个参数必须是 索引数组

2. 两个函数的第一个参数都是回调函数:
  - 方法
  - 调用一个类里面的方法
Note:

请注意,传入call_user_func()的参数不能为引用传递

<?php
function barber($type)
{
    echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>

以上例程会输出:

You wanted a mushroom haircut, no problem
You wanted a shave haircut, no problem
  - 命名空间的使用
<?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

?>
以上例程会输出:

Hello world!
Hello world!
  - 把完整的函数作为回调传入
<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'test'); /* As of PHP 5.3.0 */
?>
以上例程会输出:

[test]

相关文章

网友评论

    本文标题:PHP函数-call_user_func和call_user_f

    本文链接:https://www.haomeiwen.com/subject/zezicqtx.html