1

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 ?

2
  • 2
    See the manual: php.net/manual/en/language.oop5.static.php - personally, I think W3School to be a rather poor source for learning programming, they do a lot of .. weird things at times. Commented Jun 29, 2019 at 18:02
  • Qirel thanks. Yes, this is my point too. Is there Complete Source To Learn Php Language? Commented Jun 29, 2019 at 18:15

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.