In PHP, can I store division or multiplication along with a number?

In PHP, I can do this:

$value1 = 5; $value2 = -2; echo $value1 + $value2; // 3 

But how do I do this with multiplication or division? Sort of:

 $value1 = 10; $value2 = /2; echo $value1 (?) $value2; // 5; 

How can I deal with this situation as easily as possible?

+4
source share
3 answers

If you need to distinguish between division and multiplication,

 $value2 = 2; //or $value2 = 1/2; echo $value1 * $value2; 

Your code works with addition and subtraction, because -2 in $value2 = -2; does not mean "subtract two." This means "[add] minus two." For multiplication you need "two" or "converse to two"

+5
source

In a word, no.

In the paragraph, you can create an anonymous function to determine the value of your $value2 :

 $value1 = 5; $op_and_value2 = function($value) { return $value1 / 2; }; echo $op_and_value2($value1); # 2 

Or you can make a class to encapsulate this behavior, but it works even more.

Or you can go to the dark side and use eval .

 $value1 = 5; $value2 = "/ 2"; echo eval("return $value1 $value2;"); # 2 

(If the "dark side" was not enough hint, do not do this if you do not want everyone to hate you.)

It would be best to store the operator and value2 separately (although you can still combine them into a structure); the operator is best stored as a function (perhaps an anonymous function, as mentioned above, but with two arguments, not hard code 2 ).

+3
source

Yes, but this is an unpleasant way to do this:

You can use eval() :

 $value1 = 10; $value2 = "/2"; echo eval("return $value1 $value2;"); // 5; 

I would very carefully use eval() in code running during production. If you finish using this approach, I would suggest reading these 2 discussions:

+2
source

Source: https://habr.com/ru/post/1447633/


All Articles