【问题标题】:Overriding static members in derived classes in PHP在 PHP 中覆盖派生类中的静态成员
【发布时间】:2011-03-11 08:16:12
【问题描述】:
<?php
class Base {
  protected static $c = 'base';

  public static function getC() {
    return self::$c;
  }
}

class Derived extends Base {
  protected static $c = 'derived';
}

echo Base::getC(); // output "base"
echo Derived::getC();    // output "base", but I need "derived" here!
?>

那么最好的解决方法是什么?

【问题讨论】:

  • 将 self::$c 替换为 static::$c
  • @Artefacto 谢谢,效果很好!

标签: php inheritance static


【解决方案1】:

解决此问题的最佳方法是升级到 PHP 5.3,其中有 late static bindings 可用。如果这不是一个选项,那么很遗憾,您将不得不重新设计您的课程。

【讨论】:

  • PHP 5.3 是否与 PHP 5.2 兼容?我的服务器仍在 5.2 上运行
  • @powerboy 它是向后兼容的,这意味着为 5.2 编写的脚本大部分将在 5.3 上运行。一些小事情可能已经改变。见这里:php.net/manual/en/migration53.php
【解决方案2】:

你必须重新实现基类方法;尝试:

class Derived extends Base {
  protected static $c = 'derived';

  public static function getC() {
    return self::$c;
  }
}

如您所见,这种解决方案非常没用,因为强制重写所有子类方法。

self::$c 的值仅取决于实际实现该方法的类,而不是调用它的类。

【讨论】:

    【解决方案3】:

    根据 deceze 和 Undolog 的输入: Undolog 是正确的,对于 PHP

    但是对于 5.3 和后期的静态绑定它会起作用,只需在函数中使用 static 而不是 self - 现在它会起作用...//THX @ deceze 提示

    为我们复制过去的示例扫描 stackoverflow 用户 - 这将起作用:

    class Base {
      protected static $c = 'base';
      public static function getC() {
        return static::$c; // !! please notice the STATIC instead of SELF !!
      }
    }
    
    class Derived extends Base {
      protected static $c = 'derived';
    }
    
    echo Base::getC();      // output "base"
    echo Derived::getC();   // output "derived"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-30
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2016-03-17
      相关资源
      最近更新 更多