一直不知道这个函数怎么用,觉得好高大上
call_user_func($class."::hello"); 第一次看到这个写法一脸懵逼,这是啥
后来我去写 写成下面
call_user_func($class,"::hello");
一直报错 说第一个参数不是个合法的回调 ,我找了好半天才发现中间是点连接 而不是逗号,还以为是两个参数
<?php
namespace Brady;
class Test
{
public function hello($name)
{
echo $name;
}
}
$class = Test::class;
#call_user_func(array($class,"hello"));
call_user_func(Test::class."::hello","hellllll");
call_user_func($class."::hello","0000088");
call_user_func(array($class,'hello'),"0000088");
class index
{
public function doindex()
{
echo "我被调用了";
}
}
$classname = index::class;
call_user_func($classname .'::doindex');
下面是php手册里面的例子 果然手册才是最牛逼的
(PHP 4, PHP 5, PHP 7)
call_user_func — 把第一个参数作为回调函数调用
Example #2 call_user_func() 的例子
<?php
function barber($type)
{
echo "You wanted a $type haircut, no problem
";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>
以上例程会输出:
You wanted a mushroom haircut, no problem You wanted a shave haircut, no problem
Example #3 call_user_func() 命名空间的使用
<?php
namespace Foobar;
class Foo {
static public function test() {
print "Hello world!
";
}
}
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!
Example #4 用call_user_func()来调用一个类里面的方法
<?php
class myclass {
static function say_hello()
{
echo "Hello!
";
}
}
$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'));
?>
以上例程会输出:
Hello! Hello! Hello!