Preforming math stored in variables

前端 未结 4 1475
借酒劲吻你
借酒劲吻你 2021-01-21 11:03

I have 3 variables like this: $first = 2; $second = 5; $operation = \'*\';

how can I programaticly assign the solution to this math problem to the $answer variable? I ha

4条回答
  •  感情败类
    2021-01-21 11:24

    If you are planning on doing this calculation often, I would strongly recommend against using the eval method and instead use the method Ionut G. Stan posted above. I know it's more complicated, but each time you run eval, PHP loads the compiler engine all over again, and so it has a high overhead cost. You'll get a major performance increase (around 10x) if you use the function dispatch approach Ionut showed. Take a look at the comments on the eval function in the PHP manual and you'll see other people who have also been saying this: http://www.php.net/eval

    I was once using eval hoping it would enable me to construct a fast templating mechanism for a web application, but calls to eval were very slow, and when I realised that eval was causing it I switched to a different approach. The speed gains were phenomenal.

提交回复
热议问题