PHP Classes: when to use :: vs. ->?

后端 未结 7 2172
暗喜
暗喜 2020-12-04 19:36

I understand that there are two ways to access a PHP class - \"::\" and \"->\". Sometime one seems to work for me, while the other doesn\'t, and I don\'t understand why.

相关标签:
7条回答
  • 2020-12-04 20:31

    Sourcing WikiPedia - Class

    In object-oriented programming, a class is a programming language construct that is used as a blueprint to create objects. This blueprint describes the state and behavior that the created objects all share. An object created by a class is an instance of the class, and the class that created that instance can be considered as the type of that object, e.g. a type of an object created by a "Fruit" class would be "Fruit".

    The :: operator accesses class methods and properties which are defined in php using the static keyword. Class const are also accessed using ::

    The -> operator accesses methods and properties of an Instance of the class.

    If the function operates on an instance, you'll be using ->. If it operates on the class itself, you'll be using ::

    Another use of :: would be when you want to call your parent functions. If one class inherits another - it can override methods from the parent class, then call them using parent::function()

    0 讨论(0)
提交回复
热议问题