静态变量和静态方法

静态变量

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

思路:
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.静态方法不能操作非静态变量.

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

posted @ 2018-02-06 21:55  TangYJun  阅读(273)  评论(0编辑  收藏  举报