self与$this的功能极其相似,但二者又不相同。$this不能引用静态成员和常量。self更像类本身,而$this更像是实例本身。
一. self
1.self可以访问本类中的静态属性和静态方法,可以访问父类中的静态属性和静态方法。用self时,可以不用实例化的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php class selfStuP{ static $instance ; public function __construct(){ self:: $instance = 'instance' ; //静态属性只能通过self来访问 } public function tank(){ return self:: $instance ; //访问静态属性 } } $str = new selfStuP(); echo $str ->tank(); echo "\n" ; ?> |
页面输出:instance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php class selfStuP{ static $instance ; public function __construct(){ self:: $instance = 'dell' ; //静态属性只能通过self来访问 } static public function pentium(){ return self:: $instance ; //静态方法也可以继续访问静态变量,访问时需 要加$ } public function tank(){ return self::pentium(); //访问静态属性 } } $str = new selfStuP(); echo $str ->tank(); echo "\n" ; ?> |
页面输出:dell
2.self可以访问const定义的常量
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php class selfStuP{ const NAME = 'tancy' ; public function tank(){ return self::NAME; } } $str = new selfStuP(); echo $str ->tank(); echo "\n" ; ?> |
页面输出:tancy
二.this
1.this可以调用本类中的方法和属性,也可以调用父类中的可以调的方法和属性,可以说除过静态和const常量,基本上其他都可以使用this联络
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php class thisStu{ public $public ; private $private ; protected $protected ; public function __construct(){ $this -> public = 'public' ; $this -> private = 'private' ; $this -> protected = 'protected' ; } public function tank(){ return $this -> public ; } public function dell(){ return $this -> private ; } public function datesrt(){ return $this -> protected ; } } $str = new thisStu(); echo $str ->tank(); echo "\n" ; echo $str ->dell(); echo "\n" ; echo $str ->datesrt(); echo "\n" ; ?> |
页面输出:
public
private
protected
总结:
一句话,self是引用静态类的类名,而$this是引用非静态类的实例名。