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?

nhaa123
  • 9,570
  • 11
  • 42
  • 63
  • 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 ? – ehanoc May 10 '12 at 08:51

2 Answers2

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());
    }
}
fivedigit
  • 18,464
  • 6
  • 54
  • 58
  • But the Base-class does not have constructor. Does this still work? – nhaa123 May 10 '12 at 07:35
  • Probably you should define `Base`'s copy constructor accepting `Base` type as a parameter – yuvin May 10 '12 at 07:36
  • 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. – fivedigit May 10 '12 at 07:36
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

Community
  • 1
  • 1
Cory Carson
  • 276
  • 1
  • 6