happy cat image

Start Web Coding

Your First step toward web coding,
Start Web Coding

change UI

Maintain the life cycle of local variables

When the function finishes running, the local variables in the function automatically disappear from memory.
You can prevent it from disappearing automatically.
Use the static keyword in a function.

Using the static Keyword

static local variable name

Let's first see without using static?

<?php
    function func(){
        $disney = 0;
        $disney++;
        return $disney;
    }

    echo func();
    echo '<br>';
    echo func();
?>

In the code above I declared a local variable disney and used the increment operator ++. Then once called, it is set to 1 by ++.
Obviously, after the function exits, the disney variable is destroyed so that no value exists. If you call 2 times but output 1, it is normal.
Here is the result:

So let's check if the local variable using the static keyword has disappeared after the function's life cycle is over.
In the same code as above, we'll use static before the variable. So the result should be 1, then 2, by ++.
Because the function stays in memory even after it exits.

<?php
    function func(){
        static $disney = 0;
        $disney++;
        return $disney;
    }

    echo func();
    echo '<br>';
    echo func();
?>

Result of the code above

php image

Unlike the first example, because the static keyword is used in the function, the variable does not disappear in memory, so the value 1 is ++ from 2, and 2 is printed when the second call is made.
So we learned about the static keyword.

강좌로 돌아가기