Does typing in PHP interfere with an application’s performance?

Asked

Viewed 182 times

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.

  • 2

    If the method argument was defined as int, what would be the function of cast for int in your body? The parameter will already be int, then it’s unnecessary. It gets even worse in the second example: you define the argument as int, check if he is int and, if it is, do the cast for int.

  • @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 ?

  • If you already do the conversion of it to int in the parameter, I see no need of if and Else.

  • Defining the type of argument already ensures that for any other informed type a TypeError.

  • 1

    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 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 ?

  • Related: https://answall.com/q/21508/57801

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.