Home > php教程 > php手册 > php static 变量的例子,phpstatic

php static 变量的例子,phpstatic

WBOY
Release: 2016-06-13 09:20:57
Original
1255 people have browsed it

php static 变量的例子,phpstatic

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

调用 代码

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

 

例子 演示需要静态变量的例子

class myobject {
public static $mystaticvar = 0;

function mymethod() {
// ::为作用域限定操作符
// 用的self作用域而不是$this作用域
// 因为$this只表示类的当前实例,而self::表达的是类的本身
self::$mystaticvar += 2;
echo self::$mystaticvar . "
";
}
}

$instance1 = new myobject();
$instance1->mymethod(); // 显示 2

$instance2 = new myobject();
$instance2->mymethod(); // 显示 4

?>

 

class myobject {
public static $myvar = 10;
}

echo myobject::$myvar;

// 结果: 10
?>


本函数没什么用处,因为每次调用时都会将 $w3sky 的值设为 0 并输出 "0"。将变量加一的 $w3sky++ 没有作用,因为一旦退出本函数则变量 $w3sky 就不存在了。要写一个不会丢失本次计数值的计数函数(www.111cn.net),要将变量 $w3sky 定义为静态的:


例子 使用静态变量的例子

function test()
{
static $w3sky = 0;
echo $w3sky;
$w3sky++;
}
?>
现在,每次调用 test() 函数都会输出 $w3sky 的值并加一。

看个实例


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"; // php 5.3.0之后可以动态调用
print bar::$my_static . "n";
$bar = new bar();
print $bar->foostatic() . "n";
?>

from:http://www.111cn.net/phper/php/php-static.htm

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template