zoukankan      html  css  js  c++  java
  • call_user_func函数

    一直不知道这个函数怎么用,觉得好高大上

    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 — 把第一个参数作为回调函数调用

     

    call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] ) : mixed

    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!
  • 相关阅读:
    Android AHandle AMessage
    android java 与C 通过 JNI双向通信
    android 系统给应用的jar
    UE4 unreliable 同步问题
    UE4 difference between servertravel and openlevel(多人游戏的关卡切换)
    UE4 Run On owing Client解析(RPC测试)
    UE4 TSubclassOf VS Native Pointer
    UE4 内容示例网络同步Learn
    UE4 多人FPS VR游戏制作笔记
    UE4 分层材质 Layerd Materials
  • 原文地址:https://www.cnblogs.com/brady-wang/p/10625437.html
Copyright © 2011-2022 走看看