首页 > Web开发 > 详细

PHP:class static

时间:2014-03-12 20:43:08      阅读:252      评论:0      收藏:0      [点我收藏+]

static关键词的一种常见用途是,当类的某个变量$var被定义为static时,那么$var就是类的变量。

这意味着:1,该类的任意一个实例对其进行修改,在该类的其它实例中访问到的是修改后的变量。

实例1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
class test
{
    static public $errno = 100;
 
    public function setErrno($errno)
    {
        self::$errno = $errno;
    }
 
    public function getErrno()
    {
        return self::$errno;
    }
}
 
$t1 = new test();
$t2 = new test();
echo $t1->getErrno()."\n";
$t1->setErrno(10);
echo $t1->getErrno()."\n";
echo $t2->getErrno()."\n";

  输出:

bubuko.com,布布扣
100
10
10
bubuko.com,布布扣

注意:test类的static变量$errno获取方式有两种:1)直接获取 test::$errno;2)通过类函数获取

这意味着:2,static变量不随类实例销毁而销毁;

实例2:

bubuko.com,布布扣
<?php
class test
{
    static public $errno = 100;

    public function setErrno($errno)
    {
        self::$errno = $errno;
    }

    public function getErrno()
    {
        return self::$errno;
    }
}

$t1 = new test();
$t2 = new test();
echo $t1->getErrno()."\n";
$t1->setErrno(10);
echo $t1->getErrno()."\n";
echo $t2->getErrno()."\n";

unset($t1, $t2);
echo test::$errno."\n";
bubuko.com,布布扣

输出:

bubuko.com,布布扣
100
10
10
10
bubuko.com,布布扣

实例2的最后两行,虽然实例$t1和$t2已经被主动销毁,但是仍然static变量$errno仍存在。

PHP:class static,布布扣,bubuko.com

PHP:class static

原文:http://www.cnblogs.com/helww/p/3596956.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!