面向对象知识点之statickeyword的使用

时间:2021-06-06 08:38:02

<?php

/*由static定义的属性和方法称为静态成员和静态方法。static定义的属性和方法是属于类的,在对象之间共享。*/

/*比如能够通过定义一个静态变量来统计类实例化了多少个对象*/

 class test{

     static $count;

     function __construct() // 定义一个构造函数

     {

         self::$count++;

     }

     static function getCount(){ //定义一个静态方法,返回静态变量$count的值

         return self::$count;

     }

     }

     test::$count=0; //初始化静态变量$count的值为0

     $test_01=new test();

     $test_02=new test();

     $test_03=new test();

     $sum=test::getCount();

     echo $sum;

     //结果3

     /*

     在类外和类内能够通过

     类名::静态成员; //訪问静态成员

     类名::静态方法; //訪问静态方法

     在类内静态方法能够通过

     self::静态成员; //訪问静态成员

     self::静态方法; //訪问静态方法

     注意:在静态方法中仅仅能訪问静态成员

     */

?>