PHP 5.3之前的静态继承 [英] Static Inheritance prior to PHP 5.3

查看:62
本文介绍了PHP 5.3之前的静态继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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之前,有没有办法做到这一点?

Is there a way to do this before PHP 5.3?

推荐答案

B->echoExtendedStaticVariable() == 'A',因为self::是在编译时而不是运行时求值的.就像您写的是A::而不是self::.

B->echoExtendedStaticVariable() == 'A' because self:: is evaluated at compile-time, not run-time. It's as if you wrote A:: instead of self::.

您想要的是一个称为后期静态绑定"的功能-之所以是后期",是因为它可以在运行时而不是在编译时确定类.

What you want is a feature called "late static binding"--it's "late" because it can determine the class at runtime instead of at compile-time.

您可以使用ReflectionClass在PHP 5.2中模拟(排序):

You can emulate this (sort-of) in PHP 5.2 using 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设置为静态方法,并期望它能够正常工作.

Note that you can only do this if you have access to an instance, so you can't make echoExtendedStaticVariable a static method and expect this to work.

这篇关于PHP 5.3之前的静态继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆