【问题标题】:Setting a variable to an operator then executing it将变量设置为运算符然后执行它
【发布时间】:2014-06-08 04:14:21
【问题描述】:

总的来说,我是 PHP 新手。我一直在弄乱这段代码,直到我想在一组中执行该函数,而不必设置和添加、sub、div、mult 函数。如何使用两个 num 集设置变量运算符?

示例伪代码:

<?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);

【问题讨论】:

  • 你不能...使用开关或功能。

标签: php function class operations


【解决方案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

【讨论】:

  • return $operand0*operand1;return $operand0+operand1; 会出现语法错误。
  • 感谢 Zerquix,现在已修复。
猜你喜欢
  • 1970-01-01
  • 2018-01-27
  • 2014-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
相关资源
最近更新 更多