Setting a variable to an operator then executing it

对着背影说爱祢 提交于 2020-01-16 19:19:26

问题


I'm new to PHP in general. I was messing with this code until I wanted to execute the function in one set instead of having to set and add, sub, div, mult function. How do I go about setting the variable operator with the two num sets?

Example pseudo code:

<?php
$Num1 = 10;
$Num2 = 5;
$operation = /;
$Sum = $Num1 $operation $Num2;
return $Sum;

Or something like:

<?php
// creating Class "Math"
class math {
    //Executing the function
    function exec($info = array()) {
      return $info['num1'] $info['operation'] $info['num2'];
    }
}

// Set info
$info = array(
    'num1' => 10,
    'num2' => 5,
    'operation' => '/'
);

//execute the OOP
$math = new math;
echo $math->exec($info);

回答1:


What you are asking for is referred to as the Strategy Pattern.

One way to do this is to define your functions

$multiply = function($operand0, $operand1) {
    return $operand0*$operand1;
};

$add = function($operand0, $operand1) {
    return $operand0+$operand1;
};

Then using your sample code:

class math {
    //Executing the function
    function exec($info = array()) {
      return $info['operation']($info['num1'], $info['num2']);
    }
}

// Set info
$info = array(
    'num1' => 10,
    'num2' => 5,
    'operation' => $add
);

//execute the OOP
$math = new math;
echo $math->exec($info); //will print 15


来源:https://stackoverflow.com/questions/24102923/setting-a-variable-to-an-operator-then-executing-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!