What is going on here in PHP with classes?

前端 未结 3 504
眼角桃花
眼角桃花 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'
    
    0 讨论(0)
  • 2021-02-09 06:11

    This has to be a bug. 100%.

    1. This is not inheritance.
    2. You should not be able to call Test1::getName() as getName() in Test1 is not static
    3. Even if you could call it, $this->name should not have access to the value in Test2.

    This breaks so many rules of OO I am seriously baffled how this got through testing. Well don for finding it!!

    0 讨论(0)
  • 2021-02-09 06:14

    PHP allows calling non-static methods as if they were static - that's a feature. PHP passes $this as an implicit parameter to such calls. Much like it does when calling a method the normal way.

    But obviously PHP doesn't check whether the statically called class inherits the current one - and that's the bug.

    This is how you could think of what PHP does:

    function Test1->getName($this = null) {
        return $this->name;
    }
    
    function Test2->getName($this = null) {
        return Test1->getName($this);
    }
    
    $test = new Test2;
    echo $test->getName($test);
    

    This behavior is wrong. The correct Test2->getName would be:

    function Test2->getName($this = null) {
        return $this instanceof Test1 ? Test1->getName($this) : Test1->getName();
    }
    
    0 讨论(0)
提交回复
热议问题