PHP静态方法和普通方法的区别

 1 <?php 
 2 header('content-type:text/html;charset=utf-8'); 
 3 /* 
 4 普通方法,存放类内,只有一份
 5  
 6 静态方法,也是存放于类内,只有一份
 7  
 8 区别在于:普通方法需要对象去调用,需要绑定$this 
 9 即,普通方法,必须要有对象,然后让对象来调用 
10  
11 而静态方法,不属于哪一个对象,因此不需要绑定$this 
12 即,不需要对象也可以调用 
13 */
14  
15 class Human{ 
16   static public $head=1; 
17   public function easyeat(){ 
18     echo '普通方法吃饭<br />'; 
19   } 
20   static public function eat(){ 
21     echo '静态方法吃饭<br />'; 
22   } 
23   public function intro(){ 
24     echo $this->name; 
25   } 
26 } 
27 Error_reporting(E_ALL|E_STRICT); 
28 //此时没有对象!方法可以执行 
29 Human::eat(); 
30 /* 
31 以下方法easyeat是一个非静态方法,就由对象来调用,但,用类来调用此方法来也可以执行,而严格状态下,此方法会执行,同时报错, 
32 Strict Standards: Non-static method Human::easyeat() should not be called statically in D:applicationPHPnow-1.5.6htdocsyan18	ypesstaticfun.php on line 32
33  
34 */
35 Human::easyeat(); 
36 /* 
37 接上,从逻辑来理解,如果用类名静态调用非静态(普通)方法 
38 比如:intro() 
39 那么,这个$this是指哪个对象呢?? 
40 因此会报错,因为找不到对象! 
41 Fatal error: Using $this when not in object context in D:applicationPHPnow-1.5.6htdocsyan18	ypesstaticfun.php on line 23 
42 */
43 Human::intro();
44  
45 /* 
46 如上分析,其实,非静态方法,是不能由类名静态调用的,但目前,php中的面向对象检测不够严格,只要静态方法中没有$this关键字,就会转化成静态方法来处理! 
47 */
48 $li=new Human(); 
49 $li->eat();
50  
51 /* 
52 总结: 
53 类》访问->静态方法(类的方法)->可以 
54 类》访问->普通方法(对象的方法)->不可以(虽然方法里不用$this关键字时,可以!但不支持这种写法)
55  
56 对象》访问》静态方法(类的方法)->可以 
57 对象》访问》普通方法(对象的方法)->可以
58  
59 */
60 ?>