给操作员设置一个变量然后执行它 [英] Setting a variable to an operator then executing it

查看:164
本文介绍了给操作员设置一个变量然后执行它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,我是PHP的新手。我一直在搞这个代码,直到我想在一个集合中执行这个函数,而不必设置和添加sub,div,mult函数。



伪代码示例:

 <?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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆