我一直想知道,使用关联数组作为翻译器是否有效(以资源和速度的方式)?
例如,假设我们有一个计算器类,它接收一个操作对象,然后调用一个要执行的函数run()
。为了检查用户尝试使用哪种操作,我们可以执行if()
或switch()
然后设置正确的操作,或者我们可以执行类似new $operations[$operation]
$operation
的操作1}}表示类似+
或-
的字符串,这些键(相应地)的$operations
数组值为Addition
和Subtraction
。通过这样做,我们可以实例化我们需要的操作,而无需编写长switch()
或if()
语句。
代码演示:
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);
}
}
}
interface Operation {
public function run($num, $current);
}
class Addition implements Operation{
public function run($num, $current) {
return $num + $current;
}
}
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();
第二种设置操作的方式是否有效(以资源和速度的方式)?
答案 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