0

How can I initialize class' base class by return value in construct? Let's say I have this as a base class:

class Base
{
    public function Foo()
    {
    }

    private $_var;
}

I also have this one static method from another class, which returns Base class:

class MyStaticClass
{
    public static function Get()
    {
        return new Base();
    }
}

and now I derive from base class it here:

class Derived extends Base
{
    public function __construct()
    {
        // Here, how can I initialize Base class with
        // object MyStaticClass returns? Something like

        parent = MyStaticClass::Get(); // This doesn't obviously work..
    }
}

Is there any solution / workaround to this?

1
  • 1
    If you have the need to do this... it seems that you need to re-think your architectural design. Why would you want to change the parent of a class during it's construction after it's after been declared as extending another class ? Can you give some contextual example ? Commented May 10, 2012 at 8:51

2 Answers 2

0

Though it seems like an uncommon way of doing it, you probably mean this:

class Derived extends Base
{
    public function __construct()
    {
        parent::__construct(MyStaticClass::Get());
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

But the Base-class does not have constructor. Does this still work?
Probably you should define Base's copy constructor accepting Base type as a parameter
Every class has a constructor. If Base only has the default constructor (which I assumed not), then this will not work, since the default constructor doesn't accept any arguments. Base's constructor needs a parameter of type Base then.
0

I have not found a way to directly do that, but if you are willing to let go of class, you can accomplish this with javascript-style OOP. See my answer on https://stackoverflow.com/a/10468793/1369091

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.