• 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变量可以在类的任意函数中使用

  • 相关阅读:
    【web性能】让css更简洁、高效
    【web性能】web性能测试工具推荐
    【web性能】js应该放在html页面的什么位置
    windows xp 无法连接wpa无线网络
    开放api设计资料收藏
    jsf组件对应表
    jsf初学selectOneMenu 绑定与取值
    jsf初学解决faces 中文输入乱码问题
    jsf初学解决GlassFish Server 无法启动
    Android 现场保护
  • 原文地址:https://www.cnblogs.com/helww/p/3596956.html
Copyright © 2020-2023  润新知