zoukankan      html  css  js  c++  java
  • 静态变量和静态方法

    静态变量

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

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

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

  • 相关阅读:
    散列
    Studio 3T破解方式
    springboot整合elasticsearch时的版本问题:
    ElasticSearch6.4.1 【Rejecting mapping update to [posts] as the final mapping would have more than 1 type】
    IP地址查询API
    拉姆达表达式 追加 条件判断 Expression<Func<T, bool>>
    类 映射 遍历大全
    jquery load(URL,FUNCTION(){}) 异步加载页面
    LINQ to Entities 不识别方法的解决方案
    当实体类属性超多时候 映射给实体类属性赋值(拉姆达+实体类映射)
  • 原文地址:https://www.cnblogs.com/aten/p/8424422.html
Copyright © 2011-2022 走看看