Calling Static Method from Class B(which extends Class A) of Class A

后端 未结 5 1620
遇见更好的自我
遇见更好的自我 2021-01-03 04:02

There was an interesting question in a practice test that I did not understand the answer to. What is the output of the following code:



        
5条回答
  •  攒了一身酷
    2021-01-03 04:05

    When you call $a->getName() you're referencing a specific object, $a, which is of class Bar and so returns "John".

    Foo::getName() isn't valid outside the function because there's no specific object.

    I'm not sure it works in PHP, but if you cast the object to the superclass as in (Foo)$a->getName() then you'd get "Andrew" as your result. You'd still be talking about the specific object ($a) but in this case of type Foo. (Note you wouldn't generally want to do this)

提交回复
热议问题