zoukankan      html  css  js  c++  java
  • 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变量可以在类的任意函数中使用

  • 相关阅读:
    怎样才能算是在技术上活跃的小公司
    jquery幻灯片--渐变
    cpm效果介绍
    我依然热爱编程
    项目开发经验终结2015/4/7
    windows上putty访问ubuntu
    ubuntu安装openssh-server
    今天犯了一个低级错误
    linux 搭建lamp环境
    能用存储过程的DBHelper类
  • 原文地址:https://www.cnblogs.com/helww/p/3596956.html
Copyright © 2011-2022 走看看