PHP: self:: vs parent:: with extends

后端 未结 2 542
予麋鹿
予麋鹿 2020-12-24 08:44

I\'m wondering what is the difference between using self:: and parent:: when a static child class is extending static parent class e.g.

class Parent {

    p         


        
相关标签:
2条回答
  • 2020-12-24 08:59
                    Child has foo()     Parent has foo()
    self::foo()        YES                   YES               Child foo() is executed
    parent::foo()      YES                   YES               Parent foo() is executed
    self::foo()        YES                   NO                Child foo() is executed
    parent::foo()      YES                   NO                ERROR
    self::foo()        NO                    YES               Parent foo() is executed
    parent::foo()      NO                    YES               Parent foo() is executed
    self::foo()        NO                    NO                ERROR
    parent::foo()      NO                    NO                ERROR
    

    If you are looking for the correct cases for their use. parent allows access to the inherited class, whereas self is a reference to the class the method running (static or otherwise) belongs to.

    A popular use of the self keyword is when using the Singleton pattern in PHP, self doesn't honour child classes, whereas static does New self vs. new static

    parent provides the ability to access the inherited class methods, often useful if you need to retain some default functionality.

    0 讨论(0)
  • 2020-12-24 09:05

    self is used to call static function and manipulate static variables, which are class specific not object specific.

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