Reputation: 7488
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
Reputation: 552
Dependency Injection pattern solve your problem elegantly. Check Pimple on GitHub for minimalist but efficient solution or use symfony2 Dependency Injection Component.
Using dependency injection container you avoid coupling or can pass an Interface instead a class.
Upvotes: 1
Reputation: 1635
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