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