PHP 5.2中的类继承:覆盖扩展类中的静态变量? [英] Class inheritance in PHP 5.2: Overriding static variable in extension class?

查看:186
本文介绍了PHP 5.2中的类继承:覆盖扩展类中的静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够在从基类扩展基类的类中使用静态变量集。

I need to bea be able to use a static variable set in a class that extends a base class... from the base class.

考虑一下:

class Animal {
    public static $color = 'black';

    public static function get_color()
    {
        return self::$color;
    }
}

class Dog extends Animal {
    public static $color = 'brown';
}

echo Animal::get_color(); // prints 'black'
echo Dog::get_color(); // also prints 'black'

这在PHP 5.3.x中非常有效( Dog :: get_color()打印'brown')因为它有后期静态绑定。但是我的生产服务器运行PHP 5.2.11,所以我需要调整我的脚本。

This works wonderfully in PHP 5.3.x (Dog::get_color() prints 'brown') since it has late static binding. But my production server runs PHP 5.2.11 and so I need to adapt my script.

解决这个问题是否有一些相当不错的解决方法?

Is there a somewhat pretty workaround to solve this issue?

干杯!

Christoffer

Cheers!
Christoffer

编辑:目标

如下所述,这是我想要完成的一个非常简化的例子。如果我向你提供了我用来解决问题的两个选项(以及问题本身),有人可能会有一个与我不同的解决方案...

As noted below, this is a very much simplified example of what I am trying to accomplish. If I provide you with the two options I have used to solve my problem (and the problem itself) someone might have a different solution than I...

我已经建立了一个基本数据库模型,包含find,find_by和find_all(所有静态)等函数。

I have built a base database model that contains functions like "find", "find_by" and "find_all" (all static).

在PHP 5.3中有一个名为<$ c的函数$ c> get_called_class()我当前用它来确定被调用类的名称,然后使用它来映射正确的数据库表。 Ex class User 将指向 users

In PHP 5.3 there is a function called get_called_class() which I currently use to determine the called class's name, and then use it to map against the correct database table. Ex class User would point to users.

< PHP 5.2.x中不存在code> get_called_class(),我发现的hack实现非常不可靠。然后我转向在包含类名的所有模型类中使用静态变量的这个选项。

get_called_class() doesn't exist in PHP 5.2.x and the hack implementations I've found are very unreliable. Then I turned to this option of using a static variable in all model classes which contain the class name.

推荐答案

可悲的是,在PHP之前5.3无法模拟后期静态绑定。如果那些是实例变量和方法,唯一可以让继承按预期工作的方法。

Sadly, before PHP 5.3 there's no way to simulate late static binding. The only way you can get the inheritance to work as you intend is if those are instance variables and methods.

这篇关于PHP 5.2中的类继承:覆盖扩展类中的静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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