Wilson
Wilson

Reputation: 67

PHP What is Static keyword

What is static keyword in function ?

w3school

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.

i don't undrstand , can anyone show me some code to undrstand it ?

Upvotes: 1

Views: 151

Answers (1)

HTMHell
HTMHell

Reputation: 6006

static has two different uses:

1. For classes:

Make a method or a property accessible without needing an instantiation of the class.

<?php
class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

Foo::aStaticMethod(); 

2. For functions:

A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

<?php
function test()
{
    static $a = 0;
    echo $a;
    $a++;
}
test(); // 0
test(); // 1
test(); // 2

Without static:

<?php
function test()
{
    $a = 0;
    echo $a;
    $a++;
}
test(); // 0
test(); // 0
test(); // 0

It's a good practice to use it when you can, instead of filling the global scope with junk.

Upvotes: 2

Related Questions