The functions of self and $this are very similar, but they are different. $this cannot refer to static members and constants. self is more like the class itself, and $this is more like the instance itself.
1. self
1.self can access the static properties and static methods in this class and can access Static properties and static methods in the parent class. When using self, you do not need to instantiate
<?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"; ?>
Page output: instance
<?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"; ?>
Page output: dell
2.self can access const definitions The constant
<?php class selfStuP{ const NAME = 'tancy'; public function tank(){ return self::NAME; } } $str = new selfStuP(); echo $str->tank(); echo "\n"; ?>
page output: tancy
二.this
1.this can To call methods and properties in this class, you can also call adjustable methods and properties in the parent class. It can be said that except for static and const constants, basically everything else can be contacted using this contact
<?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"; ?>
Page output:
public
private
protected
Summary:
In one sentence, self is the class name that refers to the static class. And $this is the instance name that refers to the non-static class.
Related recommendations:
Detailed explanation of the usage and access qualifiers of $this in PHP
Detailed explanation of the difference between self and $this in PHP
The above is the detailed content of The use of self and this in php. For more information, please follow other related articles on the PHP Chinese website!