Blogger Information
Blog 263
fans 3
comment 2
visits 113071
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
call_user_func用法(涉及参数的变量替换以及类和命名空间和匿名函数)
福哥的博客
Original
1539 people have browsed it

1. 指定函数的参数调用

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

call_user_func('barber','shave');
?>

2.变量作为参数的函数调用

<?php
error_reporting(E_ALL);

function increment (&$var){
    $var++;
}
$a = 0;
call_user_func('increment',$a);
echo $a."";

call_user_func_array('increment',array(&$a));//php5.3以上
echo $a."";
//0 1
?>

3. call_user_func() 用于命名空间

<?php
//call_user_func() using namespace name
namespace Foobar;

class Foo{
    static public function test(){
        print("Hello world!");
    }
}
call_user_func(__NAMESPACE__.'\\'.'Foo::test');
call_user_func(array(__NAMESPACE__.'\\'.'Foo','test'));
//输出Hello world!Hello world!
?>

4. call_user_func() 调用类的方法

<?php
//Using a class method with call_user_func()
class myclass{
    static function say_hello(){
        echo "Hello!";
    }
}
$classname="myclass";

call_user_func(array($classname,'say_hello'));
call_user_func($classname.'::say_hello');

$myobject = new myclass();
call_user_func(array($myobject,'say_hello'));
//输出Hello! Hello! Hello!
?>

5. call_user_func() 调用匿名函数并指定参数方法

<?php
call_user_func(function($arg){print "[$arg]";},'test');
//输出[test]
?>


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post