Where's the difference between self and $this-> in a PHP class or PHP method?
在php类或php方法中,
例子:
我最近看到了这个代码。
1 2 3 4 5 6 7 8 | 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; } |
但我记得
此外,通常不能从静态方法访问实例成员。意思是,你不能
1 2 3 | static function something($x) { $this->that = $x; } |
因为静态方法不知道您引用的是哪个实例。
换句话说,使用self表示静态,而这表示非静态成员或方法。
$this->处理扩展类时,self会引用当前的作用域u extended,self总是引用父类,因为它不需要实例来访问类方法或让它直接访问类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php class FirstClass{ function selfTest(){ $this->classCheck(); self::classCheck(); } function classCheck(){ echo"First Class"; } } class SecondClass extends FirstClass{ function classCheck(){ echo"Second Class"; } } $var = new SecondClass(); $var->selfTest(); //this-> will refer to Second Class , where self refer to the parent class |
您可以查看静态关键字(引用几行):
Declaring class properties or methods
as static makes them accessible
without needing an instantiation of
the class. A property declared as
static can not be accessed with an
instantiated class object (though a
static method can)...
Static properties cannot be accessed
through the object using the arrow
operator ->.
并且,从页面属性(引用):
Within class methods the properties,
constants, and methods may be accessed
by using the form$this->property
(whereproperty is the name of the property) unless the access is to a
static property within the context of
a static class method, in which case
it is accessed using the form
self::$property .
$这用于调用类的实例,其中self::主要用于调用类内的常量变量。