AlexandrX
AlexandrX

Reputation: 838

Partially override static member (array) - is this possible?

Lets say I have some base class with static member - array:

class BaseClass {
    public static $definition = array(
        'id' => array(type => 'int', 'required' => true),
        'field1' => array(type => 'string', 'required' => true),
        'field2' => array(type => 'bool', 'required' => true),
        // and over8000 array items
    );
}

Then I create the child class, and I want to override this static array, BUT I need to chenge only one array item. Is there a way not to copy-paste whole "over8000" items for the sake of only one changed item?

In other words, I want NOT this

class ChildClass extends BaseClass {
    public static $definition = array(
        'id' => array(type => 'int', 'required' => true),
        'field1' => array(type => 'string', 'required' => false), // the only changed one
        'field2' => array(type => 'bool', 'required' => true),
        // and over8000 unchanged
    );
}

but something more compact, like this:

class ChildClass extends BaseClass {
    // yes I know this is invalid, lets call this a "pseudocode"
    public static $definition['field1']['required'] = true;
}

Is there a way?

Thanks in advance.

P.S. this member cound be accessed in static context ( ChildClass::$definition['field1']; ), so this is not enough to apply change in constructor;

P.P.S. just to clarify: I'm working with engine with all it's "features" as is. And such static members, that even can be accessed in static context - are the parts of engine, that I cant change.

Upvotes: 0

Views: 90

Answers (1)

Ihor Burlachenko
Ihor Burlachenko

Reputation: 4905

It is a default property value and you can't have any expressions when defining properties. So there is no way to modify the array when defining a child class.

Since it is a static property you can add the following code after class and it will be executed after the class is defined:

class ChildClass extends BaseClass {
    public static $definition;
}

ChildClass::$definition = array_merge(BaseClass::$definition, array(
    'field1' => array(type => 'string', 'required' => false)
));

Not a good approach but it works if that's what you need.

Upvotes: 1

Related Questions