一直不知道這個函數怎么用,覺得好高大上
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\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
Example #3 call_user_func() 命名空間的使用
<?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!
Example #4 用call_user_func()來調用一個類里面的方法
<?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'));
?>
以上例程會輸出:
Hello! Hello! Hello!
