PHP自学之路-----静态方法

静态方法

    静态方法也就类方法,静态方法属于所有对象实例的,其形式如下:

访问修饰符 static 方法名(){}

注意:在静态类方法中不能访问非静态属性(变量)。 

在类外部 : 类名::类方法名 或者对象名-〉类方法名

在类内部:  类名::类方法名  或者 self::类方法名

 案例:

[php] view plain copy
 
 print?
  1. <?php  
  2.     //静态方法的使用  
  3.     class Student{  
  4.         public static $fee=0;  
  5.         public $name;  
  6.         //构造函数  
  7.         function __construct($name){  
  8.             $this->name=$name;  
  9.             echo "初始化变量<br/>";  
  10.         }  
  11.   
  12.         public static function enterSchool($ifee){  
  13.             self::$fee+=$ifee;  
  14.         }  
  15.         public static function getFee(){  
  16.             //return self::$fee;  
  17.             return Student::$fee;  
  18.         }  
  19.         //下面写法是不正确的,静态方法只能操作静态变量  
  20.         public static function test(){  
  21.             echo $this->name;  
  22.         }  
  23.   
  24.     }  
  25.   
  26.     //创建学生  
  27.     $stu1=new Student("阿辉");  
  28.     //调用静态方法的方法:  
  29.     //1 通过类名直接调用。  
  30.     //Student::enterSchool(340);  
  31.     //2 通过对象调用  
  32.     $stu1->enterSchool(340);  
  33.     $stu2=new Student("佩佩");  
  34.     Student::enterSchool(30);  
  35.     echo "总学费=".Student::getFee()."||".$stu2->getFee()."<br/>";  
  36.   
  37.     Student::test();  
  38.     //报错如下:  
  39.     //Fatal error: Using $this when not in object context in /var/myphp/class/Static.class.php on line 21  
  40.   
  41. ?>  

在实际的编程中,我们往往使用静态方法去操作静态变量。
静态方法的特点:
1、  静态方法只能操作静态变量
2、  静态方法不能操作非(费)静态变量。
注意:普通成员的方法既可以操作静态变量,也可以操作非静态变量。

 

posted @ 2017-01-10 11:10  天涯海角路  阅读(95)  评论(0)    收藏  举报