What are the implications of not declaring variables in PHP?


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

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

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

The question is, is there any implication of performance, use, or otherwise that justifies avoiding these uses:

//usar um contador sem o defenir ou resetar primeiro

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

7 answers


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


No initialized variables are needed [sic; would be initialize variables ] in PHP, however it 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 (eg used in echo) are defined as an empty string and arrays become an array empty.

As you can see, the translation of the manual is crap


$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 I said and @elias, and also the manual, the second form is not considered good practice, although it works. Ideally, you should leave the initializations clear, in a standardized way (before the first use, or perhaps at the top of the scope), so that the code becomes clearer to the reader.

22.12.2013 / 15:51

I can enumerate some robustness, compatibility, and future maintenance issues that will arise when we are working without declaring the variables before using them:

  • Warnings in PHP compatibility, robustness, future maintenance

    If the developed work is stopped at a server that contains error_reporting () (error report) configured to display E_NOTICE , we will be receiving warnings of variables that are 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 to be delivered to another team or to our client for implementation. Also important when the server is managed by a person who leaves the error reports enabled by default rather than the application requesting them.

    Error example obtained:

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

    In this example, we are using the variable, and many working hours later we return to using the same variable. As we do not declare it, it is already assigned value, which will cause us to spend a lot of time figuring out why the application is giving us a different result than we expected.

    // 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) {

    In some cases, scenarios like this are within such a complex operation that can go into production, causing much more than a simple waste of time.

  • Variable name change robustness, future maintenance

    We are often writing something and thinking about something else, causing the written text to be subject to errors. Declaring the variable in conjunction with PHP warnings helps us to develop the application without letting things go like this:

    // 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 get the declared value or the value resulting from the operations performed. If we have enabled PHP prompts in the course of our application development, you will be alerted to the fact that $baanna , $sock are not declared and we quickly resolved the issue.

  • Performance speed

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

    22.12.2013 / 15:53

    Simply declare it.

    Any impact on performance is irrelevant near the impact on maintenance.

    You or someone else can get into that code snippet later and are not sure if it's right because you're not sure where the variable value comes from (is it a global one? was it copied from somewhere else and forgot to initialize? or did you write so even from the start?).

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

    22.12.2013 / 15:11

    Impact on performance

    As many have said, there is hardly any significant impact on performance.

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

    Impact on maintainability

    Declaring variables increases and legibility of the code, as a consequence, the ease of yourself or a colleague understand what has been implemented later.

    Impact on quality

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

    • Increase understanding of the code
    • Avoid hidden bugs by using uninitialized variables (can we always trust that operations with variables undefined will always be as we expect?)
    • It helps us to think better about the purpose of the variables, reducing the incidence of variables with bad and generic names. This is a subjective concept, but one good practice eases the rest.

    Good correlated 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 the entire code to understand where a "use block" begins and ends.

    • Use variables in the smallest possible scope, as there will be less confusion of values that are inadvertently changed, the logic of a 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.

    23.12.2013 / 13:33

    I think 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 use them.

    22.12.2013 / 15:39

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

    As for maintenance, declaring variables only makes me have to refactor more code. If the process is aided by an IDE, without problems. In languages like C and Java, I have already made variable declaration errors, which would not occur if I did not have to declare them.

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

    22.12.2013 / 20:55

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

    In PHP, I would be careful in case of variable declaration, just to let the programmer be aware of what the code is doing.

    A case that I believe needs to "declare" the variable in PHP would be, for example, using a reference variable when using a Closure, so as not to let the programmer (who does not know his code) p>

    Example that I find confusing:

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

    Example that I consider legible

    $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.


    function counter()
        global $counter; // Declarei
        $conter = 0;
    24.10.2015 / 23:40