静态方法
静态方法也就类方法,静态方法属于所有对象实例的,其形式如下:
访问修饰符 static 方法名(){}
注意:在静态类方法中不能访问非静态属性(变量)。
在类外部 : 类名::类方法名 或者对象名-〉类方法名
在类内部: 类名::类方法名 或者 self::类方法名
案例:
- <?php
-
- class Student{
- public static $fee=0;
- public $name;
-
- function __construct($name){
- $this->name=$name;
- echo "初始化变量<br/>";
- }
-
- public static function enterSchool($ifee){
- self::$fee+=$ifee;
- }
- public static function getFee(){
-
- return Student::$fee;
- }
-
- public static function test(){
- echo $this->name;
- }
-
- }
-
-
- $stu1=new Student("阿辉");
-
-
-
-
- $stu1->enterSchool(340);
- $stu2=new Student("佩佩");
- Student::enterSchool(30);
- echo "总学费=".Student::getFee()."||".$stu2->getFee()."<br/>";
-
- Student::test();
-
-
-
- ?>
在实际的编程中,我们往往使用静态方法去操作静态变量。
静态方法的特点:
1、 静态方法只能操作静态变量
2、 静态方法不能操作非(费)静态变量。
注意:普通成员的方法既可以操作静态变量,也可以操作非静态变量。
posted @
2017-01-10 11:10
天涯海角路
阅读(
95)
评论()
收藏
举报