Heim  >  Artikel  >  Backend-Entwicklung  >  php static 变量的例子,phpstatic_PHP教程

php static 变量的例子,phpstatic_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:13:541029Durchsuche

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/913102.htmlTechArticlephp static 变量的例子,phpstatic class test { public static function a(){} public function b(){} } $obj = new test; 调用 代码 test::a(); $obj-a(); $obj-b(); 例子 演示需...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn