The difference between this and self in php is: self calls the class, while $this calls the instantiated object. self can access static properties and static methods in this class, as well as constants defined by const, and this can call methods and properties in this class.
Difference:
self calls the class, while $this calls the instantiated object.
(Recommended tutorial:php tutorial)
Let’s explain in detail:
1. self can access the Static properties and static methods can access static properties and static methods in the parent class. When using self, you don't need to instantiate it.
Code example:
class self_test { static $instance; public function __construct(){ self::$instance = 'instance';//静态属性只能通过self来访问 } public function tank(){ return self::$instance;//访问静态属性 } } $str = new self_test(); echo $str->tank();
Result output:
instance
2. self can access constants defined by const
Code example:
class self_test { const NAME = 'tancy'; public function tank(){ return self::NAME; } } $str = new self_test(); echo $str->tank();
3. This can call methods and properties in this class, or callable methods and properties in the parent class. In addition to static properties and const constants, this can basically be called.
Code example:
class self_test { 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 self_test(); echo $str->tank(); echo ""; echo $str->dell(); echo ""; echo $str->datesrt();
Result:
public private protected
Summary: self is the class name that refers to the static class, and $this is the instance name that refers to the non-static class.
The above is the detailed content of What is the difference between this and self in php. For more information, please follow other related articles on the PHP Chinese website!