Home > Backend Development > PHP Tutorial > Example of php static variables, phpstatic_PHP tutorial

Example of php static variables, phpstatic_PHP tutorial

WBOY
Release: 2016-07-13 10:13:54
Original
1078 people have browsed it

Examples of php static variables, phpstatic

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/913102.htmlTechArticlephp static variable example, phpstatic class test { public static function a(){} public function b(){ } } $obj = new test; Calling code test::a(); $obj-a(); $obj-b(); Example demonstration requires...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template