4
It is common when one is at the beginning to come across this doubt.
I have to perform an operation that is dependent on a condition :
Example 1
$operacao = 'somar';
$valor1 = 5;
$valor2 = 10;
$saldo = null;
if($operacao == 'somar'){
$saldo = $valor1 + $valor2;
}else{
$saldo = $valor1 - $valor2;
}
if($saldo != null){
echo $saldo;
}
Example 2
$operacao = 'somar';
$valor1 = 5;
$valor2 = 10;
$saldo = null;
$valor2 *= (($operacao == 'somar') ? 1 : -1);
$saldo = $valor1 + $valor2;
if($saldo != null){
echo $saldo;
}
Question
What is the best way to accomplish this task, so that it does not occupy many lines, nor much memory?
But what about the memory?
– Guilherme Lautert
Little memory, no?
– Wallace Maxters
Regarding function, not to need to do
$var = Invert($var)
, I would change toInvert(&$var)
.– Guilherme Lautert
@Guilhermelautert there is someone who knows how to use references, rsrsrs. I don’t usually visualize usability for them, but this time I realize.
– Wallace Maxters
@Guilhermelautert What has the memory? I think would not do the function so, have to have better reason to generate side effect. In addition to what, again, could not be used in the case of the first example, they would not be equivalent, and the function would be too specific for other cases. If it simplifies the name, it loses the expressiveness that was the purpose of the function, if it goes to do something little expressive, then I prefer to write the code.
– Maniero
No, I narrowed down the name just for example, would keep yours, just wanted to comment on the pointer. As for memory, what I’d like to know is which one would use the least.
– Guilherme Lautert
I don’t know, I would have to measure, maybe it’s the same, but if the difference is so little, but so little, that it doesn’t make any difference, especially in PHP. We are no longer programming in Sinclair with 2KB when I had to use "1" where I could use number because it saved 1 precious byte :D And it would be difficult to compare because the examples are not equivalent. In theory the first should occupy just over half a dozen bytes less because it does not need to store 2 constants. But my alternative would not cause this and would probably be the same.
– Maniero
I don’t know the memory composition of PHP deeply, but I know that it wastes a lot. So it’s not worth trying to keep looking at it. If it’s relevant, go to C/C++/Assembly or something :)
– Maniero