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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?