How to use static and global variables in PHP?

3

I need the value of a variable in several functions to be able to increment and decrement the value of the variable.

I have tried to use static variable started with null value, but even changing its value, it gets null.

How do I manipulate it?

    
asked by anonymous 05.02.2015 / 12:55

3 answers

9

How to use global variable? Simple, do not use.

Global variables are problematic. It is difficult to guarantee that it will not be confused with other variables. It is difficult to understand who and when it is being altered.

Static variable

Just declare the variable as static ( static ). In this way it will have life throughout the application. If it is within a function its visibility will only be within the function and this is important. But it does not prevent it from having life throughout the run.

When the variable is declared static it is stored in a different region of the memory that is not lost when the function terminates as is the case with local variables within a function.

Here's a possible algorithm for your counter. You can certainly improve it. You can even make the increment happen inside the function if that's all you want. You can use creativity and do it in many different ways. The important thing is that you now know that it is possible to extend the life of the variable throughout the life of the application without exposing it to any application, which would be a beautiful practice.

function contador($valor){
    static $contador;
    if (isset($valor)) {
        $contador = $valor;
    }
    return $contador;
}

echo contador(1) . "\n";
$contador = contador() + 1;
echo contador($contador);

See running on ideone .

This is global status . Ideally, do not use this. But depending on the application it does not cause a real problem.

Rafael Withoeft's answer also gives another possible solution without using global or static. The only difficulty of it is that it would have to be passing the state variable throughout the application to use elsewhere. The variable has no extended lifetime out of the function where it was created. This may be bad but it can also be good. In some cases - this does not seem to be the case with the AP - this may be the best option. This is a form similar to using an object. Only the object has only one member inside, the value itself.

    
05.02.2015 / 13:13
3

You can use reference. Example:

<?php
function foo (&$var)
{
    $var++;
}

$a=5;
foo ($a);
// $a é 6 aqui
?>

Source: link

What do references do? link

    
05.02.2015 / 12:59
2

Example of using global variables !!

<?php
    $teste = "Variável 1";
    $teste2 = "teste2";
    function teste(){
        global $teste,$teste2;
        echo $teste; // Retorno será Variável 1
    }

    //Chamando a função
    teste();
    //Alterando valor da variável...
    $teste = "valor alterado...";
    teste();
?>
    
05.02.2015 / 13:02