Where's the difference between self and $this-> in a PHP class or PHP method?

后端 未结 7 1178
不思量自难忘°
不思量自难忘° 2020-12-17 09:38

Where\'s the difference between self and $this-> in a PHP class or PHP method?

Example:

I\'ve seen this code recently.

7条回答
  •  有刺的猬
    2020-12-17 09:58

    $this is used to reference methods and properties of the current instance of a class.

    self us used to reference static methods and properties, shared by all instances (and even accessible outside of any instance) of a class.


    You can take a look at Static Keyword (quoting a few lines) :

    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 ->.


    And, from the page Properties (quoting) :

    Within class methods the properties, constants, and methods may be accessed by using the form $this->property (where property 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.

提交回复
热议问题