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条)

报告相同问题?

悬赏问题

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