面向对象知识点之static关键字的使用

来源:互联网 发布:mac隐藏dock 怎么恢复 编辑:程序博客网 时间:2024/06/07 18:57
<?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::静态方法; //访问静态方法
     注意:在静态方法中只能访问静态成员
     */
?>
0 0
原创粉丝点击