我一般都是PHP的新手。我正在搞乱这段代码,直到我想在一个集合中执行该函数,而不是必须设置和添加,sub,div,mult函数。如何使用两个num set设置变量运算符?
伪代码示例:
<?php
$Num1 = 10;
$Num2 = 5;
$operation = /;
$Sum = $Num1 $operation $Num2;
return $Sum;
或类似的东西:
<?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);
答案 0 :(得分:1)
您要求的内容称为Strategy Pattern。
一种方法是定义你的功能
$multiply = function($operand0, $operand1) {
return $operand0*$operand1;
};
$add = function($operand0, $operand1) {
return $operand0+$operand1;
};
然后使用您的示例代码:
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