dongpochi9741 2018-03-30 17: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-30 18: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部