简体   繁体   中英

php static function inheritance

I want to define a base class with static functions and an extended class which calls the static methods of its parent. As an example a base class for arrays cArray with a static method Length($arr) , so a static method call

cArray::Length($myArray);

Then I want to write an extended class xArray and use it as follows:

$objArr = new xArray($arr);
$objArr->Length();

My question is whether this is ever possible. I tried many codes but all get failed for different reasons.

You should just be able to call the method statically. It will automatically call the method in the parent class, unless you have redefined the same method in the child class.

xArray::Length($arr);

To put this into code:

class cArray {

    public static function Length($myArray) { ... }

}

class xArray extends cArray {

    ...

    public function Length() {
        parent::Length($this->arr);
    }

}

While PHP will let you do this, it's a terrible idea. When extending classes, you should not change the method signatures fundamentally. Here you're overriding the static method cArray::Length which takes one argument with the non-static xArray::Length which takes no argument. That's a fundamentally different function and thereby a bad class structure. PHP will point this out to you if you enable strict errors.

You need to rethink your approach. There's no reason the method needs to be static in the base class and no reason it needs to change its signature in the extended class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM