扩展公共静态财产

时间:2019-04-02 14:50:39

标签: php

我想扩展php7.1静态属性的类,以便运行此示例。

<?php

class mother {
    const ONE   = 1;
    const TWO   = 2;
    const THREE = 3;

    public static $desc = [
        1 => 'one',
        2 => 'two',
        3 => 'three'
    ];
}

class children extends mother {
    const FOUR = 4;

    // how to "extends" mother::$desc ??? 
}

echo children::$desc[children::THREE];
echo children::$desc[children::FOUR];
exit(0);

输出:

three
Notice: Undefined offset: 4

要拥有

,我必须在“儿童”课程中添加什么?
three
four

我尝试了几种语法,但是由于我既不知道自己在做什么也不知道自己要搜索什么,所以每次尝试都失败了。 魔术功能似乎可以帮助我,但我看不到。

2 个答案:

答案 0 :(得分:4)

没有办法内联“扩展”父数组;您所能做的就是重新声明:

class children extends mother {
    const FOUR = 4;

    public static $desc = [
        1 => 'one',
        2 => 'two',
        3 => 'three',
        4 => 'four'
    ];
}

事实发生后,您可以更加动态地进行操作:

class children extends mother {
    const FOUR = 4;

    public static $desc = null;
}

children::$desc = mother::$desc + [4 => 'four'];

答案 1 :(得分:0)

deceze有一个不错的选择,或者您可以实现一个吸气剂:

class mother {
    const ONE   = 1;
    const TWO   = 2;
    const THREE = 3;

    public static $desc = [
        1 => 'one',
        2 => 'two',
        3 => 'three'
    ];
}

class children extends mother {
    const FOUR = 4;

    public static function get_desc() {
        return static::$desc + [4 => 'four'];
    }
}

echo children::get_desc()[children::THREE];
echo children::get_desc()[children::FOUR];

或者,还有一个getter和child变量:

class children extends mother {
    const FOUR = 4;
    public static $child_desc = [4 => 'four'];

    public static function get_desc() {
        return static::$desc + static::$child_desc;
    }
}