doudan4834 2013-09-17 11:14
浏览 31
已采纳

PHP:覆盖静态方法不能按预期工作

I have two php classes: TestUK and TestFR, which extends TestUK.

Both classes are used to generate requests to two different domains. But something is going wrong with the inheritence, and I fail to understand why.

I have one method named "get_domain", which is overwritten to get the domain that should actually be used. If I call it directly via TestFR::get_domain(), i receive the expected result. But if I call a method that is not overwritten by TestFR, but which uses self::get_domain(), I receive the wrong domain.

If I simply copy-and-paste the method do_stuff from TestUK to TestFR, then I get the expected result. But copy-pasting identical (!) code is just what I was trying to avoid.

What is the reason for this? I do not have that much experience with class inheritence in PHP, but I would have expected this to work without problems. Or is my approch completely flawed?

<?php
class TestUK {

    const DOMAIN_UK = 'http://www.domain.co.uk';
    const DOMAIN_FR = 'http://www.domain.fr';

    static function get_domain(){
        return self::DOMAIN_UK;
    }

    static function do_stuff(){
        echo self::get_domain();
    }

}

class TestFR extends TestUK {

    static function get_domain(){
        return self::DOMAIN_FR;
    }

}

// Works as intended:
// Expected and actual output: http://www.domain.fr
echo TestFR::get_domain();

// Does NOT work as intendes:
// Expected Output: http://www.domain.fr
// Actual Output:   http://www.domain.co.uk
TestFR::do_stuff();
?>
  • 写回答

2条回答 默认 最新

  • douping6871 2013-09-17 11:17
    关注

    This is because the keyword self refers to the class where it appears in, not to the class on which the method was called. For the latter functionality you will have to use late static binding with the static keyword:

    static function do_stuff(){
        echo static::get_domain();
    }
    

    That said, this code smells really bad. Why is everything static and not simply an instance method? Why is TestFR extending TestUK instead of both extending an abstract base class Test?

    It would be much better to convert everything to non-static methods, and as a bonus your problem would immediately disappear.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路