• 静态变量和静态方法


    静态变量

    首先我们提出一个问题:
    说,有一群小孩在玩堆雪人,不时有新的小孩加入,请问如何知道现在共有多少人在玩?请使用面向对象的思想,编写程序解决。

    思路:
    1.使用全局变量

    <?php
        global $global_nums;//定义,完游戏的全局变量
        $global_nums=0;//赋值
        class Child{
            public $name;
            function __construct($name){
                $this->name=$name;
        }
            public function join_game(){    
                global $global_nums;//声明一下使用全局变量
                $global_nums+=1;    
                echo $this->name."加入堆雪人游戏"; 
            }
        }
        //创建三个小孩
        $child1=new Child("李逵");
        $child1->join_game();
        $child2=new Child("张飞");
        $child2->join_game();
        $child3=new Child("唐僧");
        $child3->join_game();
        //看看有多少人玩游戏
        echo "<br/> 有".$global_nums;
        ?>

    2.使用静态变量

    静态的变量的基本用法

    1.在类中定义静态变量
     [访问修饰符] static $变量名;
    2.如何访问静态变量
     如果在类中访问 有两种方法 self::$静态变量名 , 类名::$静态变量名
     如果在类外访问: 有一种方法 类名::$静态变量名

    <?php

    class Child{ public $name; public static $nums=0;//定义并初始化一个静态变量 $nums function __construct($name){ $this->name=$name; } public function join_game(){ self::$nums+=1;//self::$nums 使用静态变量 echo $this->name."加入堆雪人游戏"; } } //创建三个小孩 $child1=new Child("李逵"); $child1->join_game(); $child2=new Child("张飞"); $child2->join_game(); $child3=new Child("唐僧"); $child3->join_game(); //看看有多少人玩游戏 echo "<br/> 有这".Child::$nums;

    静态方法

    在我们编程中,我们往往使用静态方法去操作静态变量.

    静态方法的特点
    1.静态方法去操作静态变量
    2.静态方法不能操作非静态变量.

    这里请注意 : 普通的成员方法,
    既可以操作非静态变量,
    也可以操作静态变量

  • 相关阅读:
    [BZOJ]2132: 圈地计划 最小割
    从最近MySQL的优化工作想到的
    Linux基本操作 9----- 认识与学习bash
    多路径配置vlome group共享存储,VG的更新。
    两位数乘法的速算方法(一)
    请对他有足够的重视——设计!
    ASP.NET中配置应用程序
    flex开发小技巧集锦
    刚制作完的SAP Sybase ASE15.7 [Sybase Central] 客户端
    Static 关键字的 5 种用法,你会几种?
  • 原文地址:https://www.cnblogs.com/aten/p/8424422.html
Copyright © 2020-2023  润新知