Home  >  Article  >  Backend Development  >  Examples of using php static variables

Examples of using php static variables

WBOY
WBOYOriginal
2016-08-08 09:33:201252browse

Examples of using php static variables

class test
{
public static function a(){}
public function b(){}
}
$obj = new test;

calling code

test::a();
$obj->a();
$obj->b();

Example Demonstrates an example that requires static variables

class myobject {
public static $mystaticvar = 0;

function mymethod() {
// :: is the scope qualification operator
// Use self scope instead of $this scope
// Because $this only represents the current instance of the class, 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 sets the value of $w3sky to 0 and prints "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 call to the test() function will output the value of $w3sky and increment it 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"; // Can be called dynamically after php 5.3.0
print bar::$my_static . "n";
$bar = new bar();
print $bar->foostatic() . "n";
?>


The above introduces examples of using PHP static variables, including related content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn