php - 数组的静态继承

标签 php oop inheritance

我很难解释我正在尝试做什么,所以我只提供一个例子

class A {
    static $data = ['a'];

    static function getData() { return static::$data; }
}

class B extends A {
    static $data = ['b'];
}

class C extends B {
    static $data = ['c'];
}

class D extends B {
    static $data = ['d'];
}

$a = new A;
$b = new B;
$c = new C;
$d = new D;

$a::getData(); // Output: Array('a'), Expected: Array('a');
$b::getData(); // Output: Array('b'), Expected: Array('a', 'b');
$c::getData(); // Output: Array('c'), Expected: Array('a', 'b', 'c');
$c::getData(); // Output: Array('d'), Expected: Array('a', 'b', 'd');

这可能吗?

编辑:我有我的数据对象,每个对象都有一组属性规则。例如一个 User 对象有一个属性 name 最多可以有 10 个符号,我在用户类的规则中定义了这个,然后所有的用户对象在他们的属性 name 即将更改。规则数组是静态的,因为它们适用于此类的所有对象。但是,例如,当我在 VIP 用户中继承它时,VIP 将需要对基本用户没有的属性有额外的规则。我需要能够扩展规则数组,但如果我在子类中定义这样的数组,它只会覆盖我也需要的父规则。

最佳答案

所以是的,有一种方法可以只使用父类方法:

class A
{
    public static $data = ['a'];

    public static function getData()
    {
        $result = static::$data;
        $class  = get_called_class();
        while ($class = get_parent_class($class)) {
            $result = array_merge($result, $class::$data);
        }

        return $result;  
    }
}

class B extends A 
{
    public static $data = ['b']; 
}

class C extends B 
{
    public static $data = ['c']; 
}

class D extends C 
{
    public static $data = ['d']; 
}

演示 here .

如果顺序很重要,则更改合并参数顺序(现在它就像在类层次结构链中一样 - 从子级到父级)

或者,利用 class_parents()

class A
{
    public static $data = ['a'];

    public static function getData()
    {
        $classes  = [get_called_class()]; //no class with name "0"
        $classes += class_parents($classes[0]);
        return call_user_func_array('array_merge', 
            array_map(
                function($class) {
                    return $class::$data;
                }, 
                $classes
            )
        );
    }
}

演示 here .这是更短的方式。所以它可以用普通数组映射来完成。不幸的是,当前类必须手动添加到迭代层次结构数组。

关于php - 数组的静态继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31695923/

相关文章:

php - 在 codeigniter 中处理多个复选框数组

php - Oracle 10g 的结果缓存

Javascript OOP : should methods be enumerable?

C++继承公共(public)和私有(private)?

c++ - 对C++多重继承感到困惑

java - 在处理继承时识别 java 对象的类型

PHP group mysql select by 两列

php - 有没有办法在多行上编写 REGEX 模式?

c++ - 如何覆盖派生类中的虚函数?

javascript - node js中的面向对象编程