简体   繁体   English

PHP 动态调用函数

[英]PHP calling functions dynamically

I am writing a program in PHP to assign a function name to a variable and invoke it dynamically.我正在用 PHP 编写一个程序来为变量分配一个函数名并动态调用它。 I have the code below, when I run the code for addition, it is showing answers for all.我有下面的代码,当我运行代码进行加法时,它显示了所有人的答案。

function multiply($val1, $val2)
{
  $mul = $val1 * $val2;
  echo $mul;
}

function divide($val1, $val2)
{
  $div = $val1 / $val2;
  echo $div;
 }

$func = plus($_POST['val1'], $_POST['val2']);
$func = minus($_POST['val1'],$_POST['val2']);
$func = multiply($_POST['val1'],$_POST['val2']);
$func = divide($_POST['val1'],$_POST['val2']);

please help.请帮忙。

With your suggested code you do not create 4 variables to be called dynamically, instead you call the 4 functions plus, minus, multiply and divide.使用您建议的代码,您不会创建 4 个要动态调用的变量,而是调用 4 个函数加、减、乘和除。 Those functins generated the output, just as you implemented them to do.这些 functin 生成了输出,就像您实现它们一样。 $func is simply always replaced by the return value of those functions. $func总是被这些函数的返回值替换。

Instead you should try something like this if you really have to use dynamic function calls:相反,如果你真的必须使用动态函数调用,你应该尝试这样的事情:

call_user_func($_POST['operation'],$_POST['val1'],$_POST['val2']);

Note that for production you really should validate the post variables values.请注意,对于生产,您确实应该验证后期变量值。

Please have a look on how to use variable functions here and check back with the complete code you`ve tried.请在此处查看如何使用变量函数并查看您尝试过的完整代码。

Maybe you`re trying to to something like this:也许你正在尝试这样的事情:

function add($one, $two)
{
   return $one + $two;
}

$funcname = "foo";
echo $funcname(1, 4);

You could also implement your functions as a closure and pass around that closure.您还可以将您的函数实现为一个闭包并传递该闭包。 If passing around a function is what you want.如果传递一个函数是你想要的。

$divide = function($val1, $val2) {
    $div = $val1 / $val2;
    echo $div;
};

$divide($_POST['val1'], $_POST['val2']);
other_function($divide, $param, $otherParam); // you could use the closure $divide inside this function.

But please don't forget to escape the user input you're using for your script.但是请不要忘记转义您用于脚本的用户输入。

Here's what you can try and make it fit in your need.这是您可以尝试并使其适合您的需要的方法。

function user_selection($operation,$op1,$op2){
   switch ($operation){
    case '+':
        return $op1 + $op2;
        break;
    case '-':
        return $op1 - $op2;
        break;
    case '*':
        return $op1 * $op2;
        break;          
    case '/':
        return $op1 / $op2;
        break;  
    }

} }

and to call above function, you can put并调用上面的函数,你可以把

  $functionName = 'user_selection';
  echo $functionName('+',1,2);

You can do different things by changing arguments,operations etc etc. For better understanding how this thing work look php manual for variable functions您可以通过更改参数、操作等来做不同的事情。为了更好地理解这件事是如何工作的,请查看变量函数的 php 手册

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM