What is going on here in PHP with classes?

前端 未结 3 511
眼角桃花
眼角桃花 2021-02-09 05:21

If I have this code, the string \"test\" is echoed. This is in PHP 5.3. Is this some oversight that shouldn\'t be relied on, or is it some way of achieving multiple inheritence

3条回答
  •  礼貌的吻别
    2021-02-09 06:03

    Just to be clear - this isn't inheritance. Test2 does not extend Test1. You statically referenced a public method of the Test1 class.

    Nonetheless, the fact that it returns 'test' is interesting to say the least. And I see where it is giving off the idea of inheritance.

    If you can't find a decent answer, I'd submit your code as a bug.

    UPDATE

    It looks like under the hood, even though you statically referenced a method of Test1, it's still being called as Test2. In the end, this is undefined behavior, and ask noted above does throw a strict warning. Still very odd, and I personally agree that it shouldn't work. But just to shed a little more insight which object it is using.

    class Test1 {
        function getName() {
            echo get_class($this);
            return $this->name;
        }
    }
    // ...
    $test = new Test2;
    echo $test->getName();
    
    // echoes 'Test2 test'
    

提交回复
热议问题