【问题标题】:Calling different functions depending on the value of a given parameter根据给定参数的值调用不同的函数
【发布时间】:2016-02-11 08:34:09
【问题描述】:

这个问题其实很简单,但解释起来有点困难,但我会尽力而为。

假设以下函数和类:

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;
    }
}

所以,我们有一个函数可以做一些事情。它有 3 个参数:

$a = 整数

$b = 也是一个整数

$whatToDo。 = 一个字符串,thisthatsomethingElse

如您所见,do_something() 中的计算需要一个通过类中的 3 个函数之一接收的值。但是被调用的函数应该由$whatToDo 中的值定义。当然,我可以创建一个如下所示的 if 或 switch 语句:

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;
}

但这看起来很可怕,如果我得到更多(实际代码可以有多达 41 个不同的“$whatToDo's”),真的很难阅读。

我想知道是否有一种方法可以使用变量来“创建”一个函数名并调用该函数,例如:

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

这样如果$whatToDo 包含“this”,它将调用doThis()

这有可能以任何必要的方式吗?

【问题讨论】:

  • 这应该像这样工作: someRandomClass::{"do" 。 $whatToDo}();但请下次尝试更好地搜索网络。来源:*.com/questions/1005857/…
  • *.com/questions/2108795/… -> call_user_func('myClassName_' . $language . '::myFunctionName');
  • @dryman 我搜索了至少 20 分钟,但如果您不知道如何描述您要查找的内容,则很难找到。 Google 不接受 SO posta 搜索参数。对不起。

标签: php


【解决方案1】:

你可以用一个变量函数来做这样的:

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

更多信息:

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

【讨论】:

  • 就是这样,很简单,但是我太笨了,找不到它。特维姆。
  • 非常简单,但请注意这只适用于 PHP 5.4 或更高版本。
  • 如果您调用someRandomClass::$fn,那么return $this->valueThis 不会像您静态调用它那样工作?
  • 完美运行。静态函数很特殊,因为不需要实例,但它可以毫无问题地工作。请参阅文档中的第 3 个示例:php.net/manual/en/functions.variable-functions.php
【解决方案2】:

您可以使用变量的值来调用函数,例如

function a(){ echo "Testing"; }
$b="a";
$b();

这会回显Testing

【讨论】: