self和$ this->之间的区别在哪里?在一个PHP类或PHP方法? [英] Where's the difference between self and $this-> in a PHP class or PHP method?
问题描述
PHP类或PHP方法中self
和$this->
之间的区别是什么?
Where's the difference between self
and $this->
in a PHP class or PHP method?
示例:
我最近看过这段代码.
I've seen this code recently.
public static function getInstance() {
if (!self::$instance) {
self::$instance = new PDO("mysql:host='localhost';dbname='animals'", 'username', 'password');;
self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$instance;
}
但是我记得$this->
指向一个类的当前实例(对象)(可能也是错误的).但是,有什么区别?
But I remember that $this->
refers to the current instance (object) of a class (might also be wrong). However, what's the difference?
推荐答案
$this
引用该类的实例,这是正确的.但是,还有一种叫做静态的东西,对于该类的所有实例都是相同的. self::
是这些属性和功能的访问器.
$this
refers to the instance of the class, that is correct. However, there is also something called static state, which is the same for all instances of that class. self::
is the accessor for those attributes and functions.
此外,您通常不能从静态方法访问实例成员.意思是,您不能
Also, you cannot normally access an instance member from a static method. Meaning, you cannot do
static function something($x) {
$this->that = $x;
}
因为静态方法不会知道您要引用哪个实例.
because the static method would not know which instance you are referring to.
这篇关于self和$ this->之间的区别在哪里?在一个PHP类或PHP方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!