Reputation: 67
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
Reputation: 6006
static
has two different uses:
Make a method or a property accessible without needing an instantiation of the class.
<?php
class Foo {
public static function aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();
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