使用关联数组作为翻​​译器

时间:2014-10-03 13:08:49

标签: php arrays associative-array

我一直想知道,使用关联数组作为翻​​译器是否有效(以资源和速度的方式)?

例如,假设我们有一个计算器类,它接收一个操作对象,然后调用一个要执行的函数run()。为了检查用户尝试使用哪种操作,我们可以执行if()switch()然后设置正确的操作,或者我们可以执行类似new $operations[$operation] $operation的操作1}}表示类似+-的字符串,这些键(相应地)的$operations数组值为AdditionSubtraction。通过这样做,我们可以实例化我们需要的操作,而无需编写长switch()if()语句。

代码演示:

Calculator.php中

class Calculator {

    protected $result = null,
              $operands = [],
              $operation;


    public function setOperands() {
        $this->operands = func_get_args();
    }

    public function setOperation(Operation $operation)
    {
        $this->$operation = $operation;
    }

    public function calculate() {

        foreach($this->operands as $num) {

            if( ! is_number($num))
                throw new \InvalidArgumentException;

            $this->result = $this->operation->run($num, $this->result);
        }

    }

} 

Operation.php

interface Operation {
    public function run($num, $current);
}

Addition.php

class Addition implements Operation{

    public function run($num, $current) {
        return $num + $current;
    }

} 

Subtraction.php

class Subtraction implements Operation {

    public function run($num, $current) {
        return $num - $current;
    }

}

现在,当我们使用这些类时:

$calculator = new Calculator();

// input from user
$operation = "+";


$calculator->setOperands(1,2,3);

/**
 * One way to set the operation
 */

// set the operation
switch($operation) {

    case '+':
        $calculator->setOperation(new Addition);
        break;
    case '-':
        $calculator->setOpration(new Subtraction());
        break;
    // and so on..

}

$calculator->calculate();

/**
 * Second way to set the operation
 */

$operations = ['+' => 'Addition', '-' => 'Subtraction']; // can add more

$calculator->setOperation(new $operations[$operation]);

$calculator->calculate();

第二种设置操作的方式是否有效(以资源和速度的方式)?

1 个答案:

答案 0 :(得分:0)

让我想我有一个数组

$acronyms = ['AFAIK' => 'As far as I know', 'MVP' => 'Most valuable player'];

要翻译的字符串

$string = "AFAIK I do the MVP";

现在我会这样做

echo strtr($string,$acronyms);

现在我的输出将是

As far as I know I do the Most valuable player