0

I have an abstract superclass.

abstract class SuperClass{

    public static function loadInstanceFromText(){

        $instance = new self();
        // do some stuff, etc.
        return $instance;

    }

}

obviously, calling that method is impossible when referencing SuperClass, but I also have a child

class ChildClass extends SuperClass{

}

Where I would expect it to work. I call the following function:

ChildClass::loadInstanceFromText();

However, it doesn't work, because the super is attempted to be instantiated, not ChildClass. Is there any workaround for that? Because that loadInstanceFromText is complex but basically should be the same in all inheritances.

1 Answer 1

2

The keyword self represents the class in which it is declared. Therefore, in this case, new self() is going to create a new SuperClass, which is impossible because it is abstract.

On the other hand, the keyword static represents the calling class. This is called "Late Static Binding" and is supported since version 5.3. So, you can use new static() which will create a new ChildClass as you expect.

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

Comments

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.