After hours looking for solutions and patterns, it's time for me to ask the pros.
I'd love to order my object in a logical hierarchy, but still want to be able to access properties of the parent object. A simple example how I'd love to have it work...
class car {
public $strType; // holds a string
public $engine; // holds the instance of another class
public function __construct(){
$this->type = "Saab";
// Trying to pass on $this to make it accessible in $this->engine
$this->engine = new engine($this);
}
}
class engine {
public $car;
public function __construct($parent){
$this->car = $parent;
}
public function start(){
// Here is where I'd love to have access to car properties and methods...
echo $this->car->$strType;
}
}
$myCar = new car();
$myCar->engine->start();
What I won't achieve is that a method in engine can access the 'parent' car properties. I managed to do so like this, but I believe that is very very ugly...
$myCar = new car();
$myCar->addParent($myCar);
From within the addParent MethodI would be able to pass the instance on to the engine object. But that can't be the clue, can it? Is my whole idea queer?
I don't want engine to inherit from car because a car has lots of methods and properties and engine has not. Hope you get what I mean.
Hoping for hints, Cheers Boris
As @Wrikken mentioned, the correct syntax would be
echo $this->car->strType;
type
does not seem to be a member ofcar
, but if you changed it the line toThen the statement in question should now echo "Saab"
Though I think good practice here would be to not have the engine class contain a car object, just the car class should contain an engine object. And the properties would be better off as
private
. So you could have a car method likeWhere
engine::start()
returns a boolean.