dongpochi9741 2018-03-31 01:53 采纳率: 100%
浏览 109
已采纳

如何通过变量调用函数

I hope this question is not too simple, but I have no idea how to do this

$book = 'book';
$car = 'car';

function $book()
{ 
 return "Hello, world!";
}
function $car()
{
 return "WoW , The red car";
}
  • 写回答

4条回答 默认 最新

  • drd94483 2018-03-31 02:06
    关注

    You can call a function with variable name like this:

    Variable functions

    <?php
        $a = 'book';
    
        function book() {
            echo 'book function';
        }
    
        // this is equivalent to book()
        $a();
    

    So to expand a little bit:

    <?php
    $functions = ['book', 'car'];
    
    function book() {
        return "Hello, world!";
    }
    
    function car() {
        return "WoW , The red car";
    }
    
    foreach ($functions as $function) {
        echo $function() .'<br>';
    }
    

    The OUTPUT would be:

    Hello, world!
    WoW , The red car
    

    Another way of doing it to get same output:

    Anonymous functions

    $book = function() {
        echo 'book function';
    };
    
    $book();
    

    In this case, the above function doesn't have an actual name and is represented by a variable.

    And let me give you an example:

    <?php
        $book = function() {
            echo 'book function';
        };
    
        $a = $book;
    
        echo $a();
    

    So, to expand in the same manner:

    <?php
    $functions = ['book', 'car'];
    
    $book = function () {
        return "Hello, world!";
    };
    
    $car = function() {
        return "WoW , The red car";
    };
    
    foreach ($functions as $function) {
        echo ${$function}(). '<br>';
    }
    

    DEMO:

    http://sandbox.onlinephpfunctions.com/code/1972f1acd72984d459efbfb308680aaa9d7a1fad

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊