PHP:class static

简介

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

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

实例1:

<?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()."
";
$t1->setErrno(10);
echo $t1->getErrno()."
";
echo $t2->getErrno()."
";

  输出:

100
10
10

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

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

实例2:

<?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()."
";
$t1->setErrno(10);
echo $t1->getErrno()."
";
echo $t2->getErrno()."
";

unset($t1, $t2);
echo test::$errno."
";

输出:

100
10
10
10

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

说明3:static变量和static成员函数是完全不同的两个东西,static成员函数要求更严格,static变量可以在类的任意函数中使用

原文地址:https://www.cnblogs.com/helww/p/3596956.html