10
I need to call a function that can return false or a value, and in case it returns the precise value manipulate it.
So I made a code similar to the one below:
//A função que é chamada é muito mais complexa do que essa, estou utilizando apenas como exemplo para a demonstração.
public function divisao($a,$b){
if($b > 0){
return $a / $b;
}else{
return false;
}
}
//Em outro trecho do código
....
if($resultado = divisao($variavel1,$variavel2)){
//Faça alguma coisa com o resultado
}else{
//Faça outra coisa
}
...
My question giving focus to the latter if
would be: is a good practice to put the return of the function already assigning it to the variable and testing everything in the same line (within the if
)? If not, why not be good practice?
I know the code could be written as follows:
$resultado = divisao($variavel1,$variavel2);
if($resultado){
//Faça alguma coisa com o resultado
}else{
//Faça outra coisa
}
Your explanation is excellent.
– Marcos Paulo Nogueira
On the question of the type of return, the situation is not similar to the use of types nullable in typed languages? The use of these types can be a problem in them?
– bfavaretto
Not exactly, it’s a problem, but apparent, because it breaks the application (in modern languages, like C# 8, already indicates in compilation that will give problem), in PHP it only runs something in an unexpected and wrong way. But the problem is not that language is dynamic, it’s that it’s weak. If it had strong typing, even if it was dynamic, it would give an error because receiving a 0 where one expects a boolean to break the typing. Returning types differts is no problem, treating two types as if it were the same thing is problem.
– Maniero