What are the implications of not declaring variables in PHP?

Asked

Viewed 3,681 times

43

In php I can do this without declaring/defining variables:

echo($foo);  //resolve: vazio, sem nada
$foo++;
echo($foo);  // resolve: 1

Using var_dump() the same gives, respectively NULL and 1.
If I use settype($foo, "integer"); before , the same gives 0and 1.

The point is, is there is some performance, use or other implication that justifies avoiding these uses:

//usar um contador sem o defenir ou resetar primeiro
$foo++;

// adicionar elementos a uma array 
// sem os defenir $bar = array('2010'=>0,'2011'=>0); primeiro
$bar['2010']++; 
$bar['2010']++;
$bar['2011']++;  // ou $bar['2011'] = 'blah';
// resolve: array(2) { [2010]=> int(2) [2011]=> int(1) }
  • 1

    As poetic as it is, I agree that the issue has made the question clearer. I will not answer the question because it is not what you expect, but you should always do what is most readable, which better indicates the intention, and declare variables, even if it is not necessary, is a way of legibility and containment of mysterious bugs. Performance should be the last concern, in general almost never when it comes to PHP.

  • For an update of this discussion: The variables were not officially regulated in any PSR, which in my opinion should be in [PSR-1](http://www.php-fig.org/psr/psr-1 "Basic Coding") and [PSR-2](http://www.php-fig.org/psr/psr-2 "Coding Style") Therefore, good practices / performance / usage, goes from the programmer to my view. I liked all the answers given here, but, everything really depends on the need of the program.

7 answers

42


Strictly speaking, there is no variable declaration in PHP. That is, there is no one in the language statement as var to declare variables. In practice, variables are initialized in the first use. According to the manual:

Initialized variables are not required [sic; would be incialize variables] in PHP, however, is a great practice. Uninitialized variables have [sic; have] a default value of its type depending on the context in which they are used [sic; they are used] - [the] boolean pattern is FALSE, integer and floating point is zero, strings (e.g. used in echo) are defined as an empty string and arrays become an empty array.

As you can see, the translation of the manual sucks

Therefore:

$foo = 1; // inicializa a variável e atribui valor 1
$bar++;   // inicializa a variável, e por inferência de tipos ela é
          // inicializada como 0 antes de ser incrementada

As you said and @Lias, and also the manual, the second form is not considered good practice, although it works. The ideal is to make the initializations clear, in a standardized way (before the first use, or perhaps at the top of the scope), so that the code is clearer for those who read.

  • What is this 'foo' and 'bar' I see so much around?

  • 4

    @Joaopaulo They are names used in examples for any variables, such as X and Y. See (in English) http://en.wikipedia.org/wiki/Foobar

20

I can list some problems of robustness, compatibility and future maintenance that will arise when we are working without declaring variables before using them:

  1. Warnings in PHP compatibility, robustness, future maintenance

    If the developed work ends up on a server that contains the error_reporting() (bug report) configured to display E_NOTICE, we will be receiving warnings of variables being used without first being declared.

    // Reportar E_NOTICE pode ser muito bom (para reportar variáveis ​​
    // não inicializadas ou apanhar erros de digitação nos nomes das variáveis ​​...)
    error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
    

    This is particularly important if the work we do is going to be delivered to another team or to our client for implementation. Also important when the server is managed by a person who leaves bug reports enabled by default instead of the application requesting the same.

    Example of error obtained:

    Notice: Undefined variable: banana in /john/doe/meu_ficheiro.php on line 4
    
  2. Use of variables with the same name robustness, future maintenance

    In this example, we are using the variable, and many working hours later we go back to using the same variable. As we do not declare it, it is already with an assigned value, which will take us a lot of time to find out why the application is presenting us with a different result than we expected.

    <?php
    
    // linha nº 25 do nosso ficheiro
    // valor da variável banana vem de base de dados por exemplo
    $banana = 100;
    
    for ($i = 1; $i <= $banana; $i++) {
      echo "O macaco comeu a banana nº ".$i;
    }
    
    
    // linha nº 1200 do nosso ficheiro
    // temos que trabalhar novamente bananas, então
    $macacos = recolheMacacos();
    
    while ($macacos <= $controloQualquer) {
        $banana++;
    }
    
    ?>
    

    In some cases, scenarios like this are within such a complex operation that they can move to production, causing far more than a simple waste of time.

  3. Changing the variable name robustness, future maintenance

    Often we are writing something and thinking about something else, giving rise to the text being subject to errors. Declaring the variable in conjunction with PHP warnings help us to develop the application without missing things like this:

    <?php
    
    // linha nº 25 do nosso ficheiro
    // recolha do stock das bananas
    $banana = novoStock('bananas');
    
    
    // linha nº 1200 do nosso ficheiro
    // adicionar ao stock mais bananas que chegaram
    $stock = incrementaStock($baanna);
    
    
    // apresenta novo stock ao utilizador
    echo "Stock atual: " . $sock;
    
    ?>
    

    If the variable is declared, we know that: either we receive the declared value or the resulting value of the operations performed. If we have enabled PHP warnings in the course of developing our application, we will be alerted to the fact that $baanna, $sock are not stated and we quickly resolve the issue.


Speed of execution (Performance)

Here it is difficult to reach a consensus since there are many variables that contribute to this. But if I can think of a practical example, I will edit the answer.

16

Simply state it.

Any impact on performance is irrelevant near maintenance impact.

You or someone else can get to this code snippet later and not be sure if it’s right because you’re not sure where the value of the variable comes from (is it a global one? was copied from another place and forgot to initialize? or wrote so from the beginning?).

Initializing all your variables is an easy way to communicate the intention of your code to others, do this. In addition to being clearer, you’ll probably be avoiding errors (your and colleagues) -- for example, someone can create a global variable with the same name and interfere with the functioning of your code.

13

Impact on performance

As many have said, there will hardly be a significant impact on performance.

There will be much greater performance gains by creating better algorithms, using opcode and other relevant techniques.

Impact on maintainability

Declaring variables increases and readability of the code, hence the ease of yourself or a colleague to understand what has been implemented subsequently.

Impact on quality

The internal and external quality of the system improves for several reasons:

  • Increases the understanding of the code
  • Avoids hidden bugs by using uninitialized variables (can we always trust that operations with variables undefined will always be as we hope?)
  • It helps us to think better about the purpose of variables, decreasing the incidence of variables with bad and generic names. This is a subjective concept, but good practice facilitates others.

Related good practices

  • Declare variables with intuitive names, avoiding using explanations in comments. Many comments leave the code polluted.

  • Avoid reusing "generic variables" ($aux) at various points in the code. It’s almost the same as not declaring. This makes it very difficult to understand who is reading the code, since it is necessary to read all the code to understand where a "usage block" begins and where it ends.

  • Use variables in the smallest possible scope, as there will be less confusion of values that are inadvertently altered, from the logic of one method interfering with global values used in another method, etc. Have few global variables and important logics encapsulated in methods with local variables or at most using private class attributes.

6

I believe that the best way would be to declare the variable before using it because in the future you can avoid possible headaches when doing some editing or implementation in the code... Also because other languages require the declaration of variables before using them.

4

The more experienced say that it is good to declare variables for numerous reasons. Personally, I’ve never had a problem not declaring variables, except for lack of attention. In most cases, the above errors (name of variable entered wrong, use of variable that is not "zeroed") are liable to happen, even with declaration of variables.

As for maintenance, declaring variables only makes me have to refactor more code. If the process is aided by an IDE, no problem. In languages like C and Java, I’ve made variable declaration errors, which wouldn’t happen if I didn’t have to declare them.

On certain occasions, I choose to declare variables in PHP, when this makes it easier for another teammate to read the code. Other than that, I see no other positive or negative implications for not declaring variables.

3

In general, there is no implication. PHP is a weak typing language. Usually in the languages where the types should be declared they are required to be declared. Another case is javascript, because the declaration of it may imply in what scope you are using it.

In PHP, I would take care in variable declaration cases, just to keep the programmer aware of what the code is doing.

A case that I think is necessary to "declare" the variable in PHP would be, for example, in the use of a variable by reference when using a Closure, not to leave the programmer (who does not know his code) confused

Example that I find confusing:

DB::transaction(function () use(&$usuario) {
    $usuario = new Usuario(array('nome' => 'wallace');
});

print_r($usuario); // Usuario (object) {}

An example that I consider readable

$usuario; // Ou NULL

DB::transaction(function () use(&$usuario) {
    $usuario = new Usuario(array('nome' => 'wallace');
});

print_r($usuario); // Usuario (object) {}

Another issue is that, in PHP, it is usually really necessary to declare a variable when it comes to a global variable.

Thus:

function counter()
{
    global $counter; // Declarei
    $conter = 0;
}

Browser other questions tagged

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