dongque4778 2016-02-11 08:34
浏览 308
已采纳

根据给定参数的值调用不同的函数

The problem is actually quite easy, but somewhat difficult to explain, but I'll do my best.

Assume the following function and class:

somethingsomething.php

function do_something($a, $b, $whatToDo) {
    $value = someRandomClass::doThis();
    return $a + $b * $value;
}

someRandomClass.class.php

class someRandomClass {
    public static doThis() {
        return $this->valueThis;
    }
    public static doThat() {
        return $this->valueThat;
    }
    public static doSomethingElse() {
        return $this->valueSomethingElse;
    }
}

So, we have a function which does ... something. It gets 3 parameters:

$a = An integer

$b = Also an integer

$whatToDo. = A string, either this, that or somethingElse

As you can see, the calculation in do_something() requires a value which is received through one of the 3 functions in the class. But the function which is called should be defined by the value in $whatToDo. Of course, i could create an if- or switch-statement which would look like this:

function do_something($a, $b, $whatToDo) {
    if($whatToDo === "this") {
        $value = someRandomClass::doThis();
    } elseif ($whatToDo === "that") { 
        $value = someRandomClass::doThat();
    } elseif ($whatToDo === "somethingElse") {
        $value = someRandomClass::doSomethingElse();
    }
    return $a + $b * $value;
}

But this looks horrible and if I got more (the actual code can have up to 41 different "$whatToDo's") it's really difficult to read.

I wonder if there is a way to use a variable to "create" a function name and call that function, so something like:

function do_something($a, $b, $whatToDo) {
    $value = someRandomClass:: "do" . $whatToDo ."()";
    return $a + $b * $value;
}

so that if $whatToDo contains "this", it will call doThis().

Is that possible by any means necessary?

  • 写回答

2条回答 默认 最新

  • doumangzhen7204 2016-02-11 08:38
    关注

    You can made like this with a variable function:

     $fn = "do".$whatToDo."()"; // create a string with the function name
     $value = someRandomClass::$fn; // call it
    

    More info:

    http://php.net/manual/es/functions.variable-functions.php

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

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?