self this

面向对象编程(OOP,Object OrientedProgramming)现已经成为编程人员的一项基本技能。利用OOP的思想进行PHP的高级编程,对于提高PHP编程能力和规划web开发构架都是很有意义的。

这里我主要谈的是this,self关键字之间的区别。从字面上来理解,分别是指这、自己。先初步解释一下,this是指向当前对象的指针(可以看成C里面的指针),self是指向当前类的指针。我们这里频繁使用指针来描述

一. self
.    1.self可以访问本类中的静态属性和静态方法,可以访问父类中的静态属性和静态方法。用self时,可以不用实例化的
[php] view plain copy
 
  1. class self_test {  
  2.   
  3.     static $instance;  
  4.   
  5.     public function __construct(){  
  6.         self::$instance = 'instance';//静态属性只能通过self来访问  
  7.     }  
  8.   
  9.     public function tank(){  
  10.         return self::$instance;//访问静态属性  
  11.     }  
  12. }  
  13.   
  14. $str = new self_test();  
  15. echo $str->tank();  
页面输出:instance
[php] view plain copy
 
  1. class self_test {  
  2.   
  3.     static $instance;  
  4.   
  5.     public function __construct(){  
  6.         self::$instance = 'dell';  
  7.     }  
  8.   
  9.     static public function pentium(){  
  10.         return self::$instance;//静态方法也可以继续访问静态变量,访问时需要加$  
  11.     }  
  12.   
  13.     public function tank(){  
  14.         return self::pentium();//访问静态方法pentium()  
  15.     }  
  16. }  
  17.   
  18. $str = new self_test();  
  19. echo $str->tank();  
页面输出:dell

     2.self可以访问const定义的常量
[php] view plain copy
 
  1. class self_test {  
  2.   
  3.     const  NAME = 'tancy';  
  4.   
  5.     public function tank(){  
  6.         return self::NAME;  
  7.     }  
  8. }  
  9.   
  10. $str = new self_test();  
  11. echo $str->tank();  
页面输出:tancy

二.this
      1.this可以调用本类中的方法和属性,也可以调用父类中的可以调的方法和属性,可以说除过静态和const常量,基本上其他都可以使用this联络
  
[php] view plain copy
 
  1. class self_test {  
  2.     public $public;  
  3.   
  4.     private $private;  
  5.   
  6.     protected $protected;  
  7.   
  8.     public function __construct(){  
  9.         $this->public = 'public';  
  10.         $this->private = 'private';  
  11.         $this->protected = 'protected';  
  12.     }  
  13.   
  14.     public function tank(){  
  15.         return $this->public;  
  16.     }  
  17.   
  18.     public function dell(){  
  19.         return $this->private;  
  20.     }  
  21.   
  22.     public function datesrt(){  
  23.         return $this->protected;  
  24.     }  
  25. }  
  26.   
  27. $str = new self_test();  
  28. echo $str->tank();  
  29. echo "</br>";  
  30. echo $str->dell();  
  31. echo "</br>";  
  32. echo $str->datesrt();  
页面输出: public
       private
       protected
 
一句话,self是引用静态类的类名,而$this是引用非静态类的实例名。

猜你喜欢

转载自www.cnblogs.com/songyanan/p/9025740.html