2

I have an abstract class that has a method which uses a static function. This static function is defined in sub-classes and is different for each sub-class. Which sub-class will be used to create object is determined in the script. See super simplified code below:

abstract class fooClass implements iFooClass {    
    function getBar(){
        $bar = self::getSomething();
        return $bar;
    }        
}

interface iFooClass{
    static function getSomething();
}

class fooSubClass_A extends fooClass {
    static function getSomething() {
        //do something;
        //return something;
    }
}

class fooSubClass_B extends fooClass {
    static function getSomething() {
        //do something else;
        //return something else;
    }
}

$foo = New fooSubClass_A;
$bar = $foo->getBar();

This code gives me this error:

Fatal error: Cannot call abstract method iFooClass::getSomething() in C:\wamp\www\Classes\fooClass.php on line 12

I thought since the sub-classes have access to super-classes method getBar it would be called from the sub-class and thus have access to its static function. Apparently not. Is there a way to redo this to make it work?

1 Answer 1

2

I think at first you should implement "getSomething" method from "iFooClass" interface in "fooClass" because all interface functions must be implemented in child class, that's the basic rule of interfaces. Only after that you can include this function into another class method.

Edit: Abstract classes have ability not to implement all interface methods, if they are implemented in it's subclasses.

Edit2 When you call method with Self keyword, it calls method from class where "SELF" actually exists and not from class object from which we are calling method. That's why self::method() should be changed with static::method()

Sign up to request clarification or add additional context in comments.

4 Comments

but fooClass is abstract class that will never be really instantiated and getSomething is a static method that is only defined in children and is slightly different for each child. What implementation should I put in the abstract class fooClass? just an empty method static function getSomething(){}?
static function getSomething() { echo "All"; } i added this in fooClass and worked fine :).
is it calling fooSubClass_A static method? because that's the static method I want to be calling in the example above.
I solved this problem. You are using self in foosubClass wich means that when you call it, you call method from class where it actually exists and not from class your object is from. Change self::getbar() to static::getbar()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.