PHP学习笔记二十【静态方法】

<?php
//静态变量的基本用法
//1,在类中定义变量
//2.定义方式[访问修饰符]static 变量名
//3.访问方式self::$变量名 第二种方式,类名::$变量名
//4.在类外面访问只能通过第二种方式访问


   global $global_nums;//全局变量不能在声明的时候进行赋值
  class Child{    
     public $age;
     public $name;
     public function __construct($name)
     {
        $this->name=$name;
     }
     public function Join_game()
     {
       //声明一下要使用全局变量
       global $global_nums;
       $global_nums+=1;
       echo $this->name."加入游戏<br/>";
     }
  }
     $p1=new Child("张三");
     $p1->Join_game();
     $p2=new Child("李四");
     $p2->Join_game();
     $p3=new Child("王五");
     $p3->Join_game();
     
     echo $global_nums."<br/>";
     
     Class ChildS{
       public $name;
       public static $nums=0;//定义一个全局变量
       function __construct($name)
       {
          $this->name=$name;
       }
       public function Join_game()
       {
           self::$nums+=1;
           //或是用这种方式来访问静态变量 ChildS::静态变量
          echo $this->name."加入游戏<br/>";
       }
      
     }
      $p1=new ChildS("张飞");
       $p1->Join_game();
       $p2=new ChildS("关羽");
       $p2->Join_game();
       $p3=new ChildS("刘备");
       $p3->Join_game();
       echo "<br/>".ChildS::$nums;
 
?>
原文地址:https://www.cnblogs.com/sumg/p/4052819.html