Declare the variables at the top or near where they are used?

3

It is best to declare all variables at the very beginning of the file, even if they will only be used, I know, a thousand lines later? Or is it better to declare as the program evolves?

My case is that I'm going to merge several scripts into just one (I'm creating each function separately because it was getting too big and confusing), and I doubt whether I should just copy and paste those files, with the variables where they are (what is working), or if you get all the variables and play at the beginning of this big file, and then I'll just put the functions.

What are the advantages and disadvantages of each of these options? Does it make a difference in performance? Is there a path considered most correct?

Type, this is best:

// variáveis e função 1

$reds = $_POST ["Tredsalim"];
$redvalan = $_POST ["Treds4"];
$redvalan2 = $_POST ["Treds9"];

if ($reds == "sim") {
    $remmes += $redvalan + $redvalan2;
}

// variáveis e função 2

$difsal = $_POST ["Tdifsalim"];
$saldev = $_POST ["Tdate5"];
$saldev2 = $_POST ["Tdate9"];
$saldev3 = $_POST ["Tdate13"];

if ($saldev > 1) {
    $remmes = $saldev;
}
if ($saldev2 > 1) {
    $remmes = $saldev2;
}
if ($saldev3 > 1) {
    $remmes = $saldev3;

Or this:

// variáveis caso 1 

$reds = $_POST ["Tredsalim"];
$redvalan = $_POST ["Treds4"];
$redvalan2 = $_POST ["Treds9"];

// variáveis caso 2

$difsal = $_POST ["Tdifsalim"];
$saldev = $_POST ["Tdate5"];
$saldev2 = $_POST ["Tdate9"];
$saldev3 = $_POST ["Tdate13"];

// função 1

if ($reds == "sim") {
    $remmes += $redvalan + $redvalan2;
}

// função 2

if ($saldev > 1) {
    $remmes = $saldev;
}
if ($saldev2 > 1) {
    $remmes = $saldev2;
}
if ($saldev3 > 1) {
    $remmes = $saldev3;
    
asked by anonymous 19.04.2015 / 04:31

1 answer

3

It is probably best to ensure that all variables are declared at the beginning. This goes against what we usually recommend. But joining multiple codes is also not recommended. So since it will do something not recommended that at least try to minimize the damage and it will be minimized if you have to analyze the whole code to find out all the variables to declare at the beginning. Who knows that some bugs would be caused by overlapping variables or other conflicts.

In this specific example it is even more obvious that you should do this because deep down the variables are well-related, at bottom one group is a continuation of the other.

This should be done only for the sake of organization, it does not influence performance.

Of course, in another situation change can change the logic of the code.

If you are creating several functions in the same file, it is simpler because the variables are local, there must be everything close to it, you can not group the variables without creating new problems.

    
19.04.2015 / 05:57