PHP中静态成员的继承 [英] Inheritance of static members in PHP

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

问题描述

在PHP中,如果在父类中定义了静态属性,则无法在子类中重写它。但我想知道是否有任何解决方法。

In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class. But I'm wondering if there's any way around this.

我正在尝试为其他人(有点笨重)的函数编写一个包装器。有问题的函数可以应用于许多不同的数据类型,但每个都需要不同的标志和选项。但是99%的情况下,每种类型的默认值都足够了。

I'm trying to write a wrapper for someone else's (somewhat clunky) function. The function in question can be applied to lots of different data types but requires different flags and options for each. But 99% of the time, a default for each type would suffice.

如果可以通过继承完成,那将是很好的,而不必每次都编写新函数。例如:

It would be nice if this could be done with inheritance, without having to write new functions each time. For example:

class Foo {
    public static $default = 'DEFAULT';

    public static function doSomething ($param = FALSE ) {
        $param = ($param === FALSE) ? self::$default : $param;
        return $param;
    }
}

class Bar extends Foo {
    public static $default = 'NEW DEFAULT FOR CHILD CLASS';
}

echo Foo::doSomething() . "\n"; 
// echoes 'DEFAULT'

echo Bar::doSomething() . "\n"; 
// echoes 'DEFAULT' not 'NEW DEFAULT FOR CHILD CLASS' 
// because it references $default in the parent class :(


推荐答案

为什么使用静态作为全局变量(在这种情况下是函数)的经典例子不管语言是个坏主意。

Classic example of why using statics as globals (functions in this case) is a bad idea no matter the language.

最强大的方法是创建抽象基类Action类的多个实现子类。

The most robust method is to create multiple implementation sub classes of an abstract base "Action" class.

然后尝试并删除实例化该类实例的一些烦恼只是为了调用它的方法,你可以将它包装在某种工厂中。

Then to try and remove some of the annoyance of instantiating an instance of the class just to call it's methods, you can wrap it in a factory of some sort.

例如:

abstract class AbstractAction {
  public abstract function do();
}

class FooAction extends AbstractAction {
  public function do() {
    echo "Do Foo Action";
  }
}

class BarAction extends AbstractAction {
  public function do() {
    echo "Do Bar Action";
  }
}

然后创建一个工厂以帮助实例化函数

Then create a factory to "aid" in instantiation of the function

class ActionFactory {
  public static function get($action_name) {
    //... return AbstractAction instance here
  }  
}

然后将其用作:

ActionFactory::get('foo')->do();

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

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