Self and $this are very similar in function, but they are not the same. $this cannot reference static members and constants. Self is more like the class itself, and $this is more like the instance itself.
I. Self
1.self can access static properties and static methods in this class, and can access static and static methods in the parent class. When using self, you can not instantiate the
<?php class selfstup{ static $instance; Public Function __construct () {self :: $instance = ' instance ';//static property can only be accessed by self for public function tank () { return self:: $instance; Access static Property } } $str = new Selfstup (); echo $str->tank (); echo "\ n"; ? >
Page Output: Instance
<?php class selfstup{ static $instance; Public Function __construct () {self :: $instance = ' dell ';//static property can only be accessed by self for } static public function Pentium () { return self:: $instance; Static methods can also continue to access static variables, which need to be added $ } public function tank () { return self::p entium (); Access static Property } } $str = new Selfstup (); echo $str->tank (); echo "\ n"; ? >
Page Output: Dell
2.self can access const-defined constants
<?php class selfstup{ const NAME = ' tancy '; Public Function tank () { return self::name; } } $str = new Selfstup (); echo $str->tank (); echo "\ n"; ? >
Page output: tancy
Two. This
1.this can call methods and properties in this class, or you can call the adjustable methods and properties in the parent class, and you can say that except for static and const constants, you can basically use 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
Summarize:
In a word, self is a class name that refers to a static class, and $this is an instance name that references a non-static class.
Related recommendations:
The differences between self, static, $this and later static bindings in PHP
$this usage and Access qualifiers in PHP
A detailed explanation of the difference between self and $this in PHP