1
Out of curiosity, and by using it a lot without knowing if it is necessary, define the type of the variable is something I do in 100% of my code.
It’s usually defined by something like this:
class classe
{
private $dado;
public function dado(int $dado = 1)
{
$this->dado = (int) $dado;
return $this;
}
}
Or in rare cases where there is no object orientation:
$var = (int) 1;
The question is:
Define types in 100% of code reduces or improves performance ? (even that the gain or loss of performance is negligible)
And a second question is:
It is worth validating the type ?
Example:
class classe
{
private $dado;
public function dado(int $dado = 1)
{
if(is_int($dado) == true)
{
$this->dado = (int) $dado;
}else
{
$this->dado = die('Tipo não suportado');
}
return $this;
}
}
PS: In the example in question that I’m trying to improve performance is an abstraction layer for building pages with CSS Bootstrap 4 + JS.
If the method argument was defined as
int
, what would be the function of cast forint
in your body? The parameter will already beint
, then it’s unnecessary. It gets even worse in the second example: you define the argument asint
, check if he isint
and, if it is, do the cast forint
.– Woss
@Andersoncarloswoss Is that the code in question that I use this last option, is a code that does not give me a result, is just a layer of construction, I use these methods in another code, only so I would have an answer, then knowing exactly where it was and what the error was is an important part of the process, but going back to what you said, setting the type in the parameter is enough for the whole method ?
– AnthraxisBR
If you already do the conversion of it to int in the parameter, I see no need of if and Else.
– Lucas de Carvalho
Defining the type of argument already ensures that for any other informed type a
TypeError
.– Woss
If you force types in 100% of your PHP code, it’s a sign that you should be using another, strong typing language. About your question, I found information in English here and here.
– bfavaretto
@bfavaretto I came to think of this, because PHP gives a lot of 'freedom' to those who are programming, but a stupid question, that another language can replace php (replace in the question of having a similar semantics) to work only with web ?
– AnthraxisBR
Related: https://answall.com/q/21508/57801
– Don't Panic