Home > Article > Backend Development > Example of php static variables, phpstatic_PHP tutorial
class test
{
public static function a(){}
public function b(){}
}
$obj = new test;
Call code
test::a();
$obj->a();
$obj->b();
Example demonstrates the need for static variables
class myobject {
public static $mystaticvar = 0;
function mymethod() {
// :: Scope limiting operator
// Use self scope instead of $this scope
// Because $this only represents the current scope of the class instance, and self:: expresses the class itself
self::$mystaticvar += 2;
echo self::$mystaticvar . "
";
}
}
$instance1 = new myobject();
$instance1->mymethod(); // Display 2
$instance2 = new myobject();
$instance2->mymethod(); // Display 4
?>
class myobject {
public static $myvar = 10;
}
echo myobject::$myvar;
// Result: 10
?>
This function is not very useful because it will set the value of $w3sky to 0 and output "0" every time it is called. Increasing the variable $w3sky++ by one has no effect, because the variable $w3sky does not exist once this function exits. To write a counting function (www.111cn.net) that will not lose this count value, define the variable $w3sky as static:
Example Example of using static variables
function test()
{
static $w3sky = 0;
echo $w3sky;
$w3sky++;
}
?>
Now, each time the test() function is called, the value of $w3sky will be output and incremented by one.
Look at an example
class foo
{
public static $my_static = 'foo';
public function staticvalue() {
return self::$my_static;
}
}
class bar extends foo
{
public function foostatic() {
return parent::$my_static;
}
}
print foo::$my_static . "n";
$foo = new foo();
print $foo->staticvalue() . "n";
print $foo->my_static . " n"; // undefined "property" my_static
print $foo::$my_static . "n";
$classname = 'foo';
print $classname::$my_static . "n"; // After php 5.3.0, you can dynamically call
print bar::$my_static . "n";
$bar = new bar();
print $bar->foostatic() . "n ";
?>
from:http://www.111cn.net/phper/php/php-static.htm