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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题