Variable Operators in PHP

前端 未结 5 755
青春惊慌失措
青春惊慌失措 2020-12-07 02:15

Given this example, how would I return the result of the equation rather than the equation itself as a string?

$operator = \'+\';
foreach($resultSet as $item         


        
5条回答
  •  囚心锁ツ
    2020-12-07 03:10

    To achieve exactly that, you can use create_function

    $operator = '+';
    $func = create_function('$a,$b', "return \$a $operator \$b;");
    foreach($resultSet as $item){
        $result = $func($item, 1);
        echo $result;
    }
    

    A cleaner solution is possible with lambdas (php5.3 required)

    $func = function($a, $b) { return $a + $b; };
    foreach($resultSet as $item){
        $result = $func($item, 1);
        echo $result;
    }
    

    See also array_sum, array_reduce

    Advanced example with array_reduce and lambdas

    $ary = array(
        array('foo' => 1, 'bar' => 91),
        array('foo' => 2, 'bar' => 92),
        array('foo' => 3, 'bar' => 93),
        array('foo' => 4, 'bar' => 94),
        array('foo' => 5, 'bar' => 95),
    );
    
    $sumOfFoos = array_reduce($ary, 
        function($val, $item) { return $val + $item['foo']; } 
    );
    $sumOfBars = array_reduce($ary, 
        function($val, $item) { return $val + $item['bar']; } 
    );
    

    The main point is, that instead of 'variable operators' (which is not possible in php), you should rather use variable functions (which is possible and much more flexible).

提交回复
热议问题