Home  >  Article  >  Backend Development  >  Simple example of static variables in PHP object-oriented programming

Simple example of static variables in PHP object-oriented programming

WBOY
WBOYOriginal
2016-07-25 09:01:00842browse
Let me introduce to you an example of static variables in PHP object-oriented programming. Friends in need can refer to it.

As for what PHP object-oriented static variables are, they have been introduced a lot in previous PHP tutorials. You can review them.

Let’s look at today’s problem. There is a group of friends playing a hide-and-seek game. New children join from time to time. How do you know how many people are playing now? Please use object-oriented thinking and write a program to solve the problem.

There are two ways to solve this problem: use global variables and static variables.

<?php
    //有一群朋友在玩捉迷藏游戏,不时有新的小朋友加入,
    //请问如何知道现在共有多少人在玩?
    //请使用面向对象的思想,编写程序解决。
/*
    //1种方法使用全局变量
    
    global $global_nums;
    //先声明全局变量后再对它进行赋值
    $global_nums=0;

    class Child{
    
        public $name;
        
        //构造方法
        public function __construct($name){
            
            $this->name=$name;
        }

        //定义一个方法统计人数
        public function allPlay(){
            //先声明使用全局变量
            global $global_nums;
            $global_nums+=1;
            echo $this->name."加入游戏.<br/>";
        }
    }

    $p1=new Child("lily");
    $p1->allPlay();
    $p2=new Child("lucy");
    $p2->allPlay();
    $p3=new Child("kucy");
    $p3->allPlay();
    echo $global_nums;
    //by bbs.it-home.org
*/
  //第二在类中 使用静态变量
    class Child{        
        public $name;
        //在类中声明静态变量
        public static $allPlay=0;
    
        public function __construct($name){
            
            $this->name=$name;
        }
        
        //统计人数
        public function addPlay(){
            //在类中使用静态变量。在类中有下面2中方式访问静态变量
            //self::$静态变量名和类名::$静态变量名
            //self::$allPlay+=1;
            Child::$allPlay+=1;
            echo $this->name."加入游戏.<br/>";

        }
    }

    $p1=new Child("lily");
    $p1->addPlay();
    $p2=new Child("lucy");
    $p2->addPlay();
    $p3=new Child("kucy");
    $p3->addPlay();
    $p4=new Child("uucy");
    $p4->addPlay();

    //在类外只有一种方式访问静态变量:类名::$静态变量名
    echo Child::$allPlay;
?>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn