给操作员设置一个变量然后执行它 [英] Setting a variable to an operator then executing it
问题描述
伪代码示例:
<?php
$ Num1 = 10;
$ Num2 = 5;
$ operation = /;
$ Sum = $ Num1 $ operation $ Num2;
返回$ Sum;
或者类似:
<?php
//创建类Math
class math {
//执行函数
function exec($ info = array( )){
return $ info ['num1'] $ info ['operation'] $ info ['num2'];
//设置信息
$信息=数组(
'num1'=> 10,
'num2' => 5,
'operation'=>'/'
);
//执行OOP
$ math = new math;
echo $ math-> exec($ info);
你所要求的是< a href =http://en.wikipedia.org/wiki/Strategy_pattern =nofollow>战略模式。
一种方法这是为了定义你的函数
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $返回$操作数0 * $操作数;
};
$ add = function($ operand0,$ operand1){
return $ operand0 + $ operand1;
};
然后使用您的示例代码:
<$ p
$ {
//执行函数
function exec($ info = array()){
return $ info ['operation']($ info ['num1'],$ info ['num2']);
//设置信息
$信息=数组(
'num1'=> 10,
'num2' => 5,
'operation'=> $ add
);
//执行OOP
$ math = new math;
echo $ math-> exec($ info); //将打印15
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);
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
这篇关于给操作员设置一个变量然后执行它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!