PHP自学之路-----静态方法
静态方法
静态方法也就类方法,静态方法属于所有对象实例的,其形式如下:
访问修饰符 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 self::$fee; return Student::$fee; } //下面写法是不正确的,静态方法只能操作静态变量 public static function test(){ echo $this->name; } } //创建学生 $stu1=new Student("阿辉"); //调用静态方法的方法: //1 通过类名直接调用。 //Student::enterSchool(340); //2 通过对象调用 $stu1->enterSchool(340); $stu2=new Student("佩佩"); Student::enterSchool(30); echo "总学费=".Student::getFee()."||".$stu2->getFee()."<br/>"; Student::test(); //报错如下: //Fatal error: Using $this when not in object context in /var/myphp/class/Static.class.php on line 21 ?>
在实际的编程中,我们往往使用静态方法去操作静态变量。
静态方法的特点:
1、 静态方法去操作静态变量
2、 静态方法不能操作费静态变量。
注意:普通成员的方法既可以操作静态变量,也可以操作非静态变量。