【问题标题】:Static Inheritance prior to PHP 5.3PHP 5.3 之前的静态继承
【发布时间】:2012-01-24 18:28:46
【问题描述】:
class A
{
    static $v = "A";

    static function echoExtendedStaticVariable() {
        echo self::$v;
    }
}

class B extends A
{
    static $v = "B";
    // override A's variable with "B"
}

为什么会这样:

echo B::$v

打印“A”?

我如何让它打印“B”?

在 PHP 5.3 之前有没有办法做到这一点?

【问题讨论】:

  • 它不打印“A”,而是打印“B”。你的意思是$b = new B();$b->echoExtendedStaticVariable() === 'A'
  • 我的意思是说...一切都应该是静态的。
  • 请编辑您的原始问题,以准确说明您想要什么。

标签: php inheritance static php-5.3


【解决方案1】:

B->echoExtendedStaticVariable() == 'A' 因为self:: 是在编译时而不是运行时评估的。就好像你写的是A:: 而不是self::

您想要的是一种称为“后期静态绑定”的功能——它是“后期”,因为它可以在运行时而不是在编译时确定类。

您可以在 PHP 5.2 中使用 ReflectionClass 模拟这个(某种):

class A
{
    static $v = "A";
    function echoExtendedStaticVariable() {
        $rc = new ReflectionClass($this);
        echo $rc->getStaticPropertyValue('v');
    }
}
class B extends A
{
    static $v = "B";
}
$b = new B();
$b->echoExtendedStaticVariable(); // B

请注意,只有在您有权访问实例时才能执行此操作,因此您不能将 echoExtendedStaticVariable 设为静态方法并期望它能够正常工作。

【讨论】:

  • 在不创建对象的情况下还有其他方法吗?只是在类上运行函数?
  • 在什么类上运行什么函数?在 php
【解决方案2】:

在 PHP 5.2 中没有办法轻松做到这一点(即:不显式覆盖每个方法)。

当您调用B::echoExtendedStaticVariable 时,它会转发到A::echoExtendedStaticVariable,范围更改为A 之一,并且所有关于B 的绑定都消失了。没有回溯,没有反射,没有魔法常数,什么都没有:它都指向A

在我看来,除非真的有必要,否则应该避免使用静态成员,而且这种情况很少发生。它使您的代码难以扩展,因为依赖注入是有限的并且几乎不可能替换(除了像 Singleton 这样的 anti- 模式)。

【讨论】:

    猜你喜欢
    • 2011-03-12
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多