wintercounter
wintercounter

Reputation: 7488

Dynamic properties for abstract class

My issue is that i want to have a dynamic value (an instance of a class) in an abstract class public property.

I want to store an instance in the variable which is not allowed like this.

// Not allowed
abstract class Abs{
    public $var = new VarClass();
}

// This only works for extended childrens of course, but it should work globally.
class B extends Abs{
    function __construct(){
        $this->var = new varClass();
    }
}

I need this to be global. Sadly abstract classes can't have constructors which would be ideal... Also magic methods aren't solutions too, because the system defines class variables in runtime, so undefined variables would run into the magic methods also...

Upvotes: 1

Views: 384

Answers (2)

rernesto
rernesto

Reputation: 552

Dependency Injection pattern solve your problem elegantly. Check Pimple on GitHub for minimalist but efficient solution or use symfony2 Dependency Injection Component.

Pimple on GitHub

Using dependency injection container you avoid coupling or can pass an Interface instead a class.

Upvotes: 1

Shushant
Shushant

Reputation: 1635

Well Dependency Injection could solve your issue

abstract class Abs{
   //...
}


class B extends Abs{
    private $var;
    public function setVarClass(varClass $class){
         $this->var = $class;
    }
 }

 //example
 $classVar = new varClass;
 $b = new B;
 $b->setVarClass($classVar);

this is flexible way to solve at least tight coupling issue and remember Object are always referenced.

Upvotes: 0

Related Questions