What is going on here in PHP with classes?

前端 未结 3 509
眼角桃花
眼角桃花 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: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();
    }
    

提交回复
热议问题