What I have:
$tom = new Driver;
$bmw = new Car;
$benz = new Car;
What I want to have:
foreach (Car::$all_cars as $car) {
$tom->setRating($car, $rating); // $rating comes from user input
}
Question:
How to implement this?
Constraints:
- Number of Car objects is variable and unknown (thus no static property names in Driver class).
- Each Driver has a rating for every object in Car class.
- The rating property should be defined in Driver class intentionally.
What I think:
Class Driver {
private $cars;
public function __construct() {
$his->cars = new \stdClass();
foreach (Car::$all_cars as $car) {
$this->cars->$car = NULL;
}
}
public setRating($car, $rating) {
$this->cars->$car = $rating;
}
}
Class Car {
public static $all_cars = array();
public $name;
public function __construct($name) {
$this->name = $name;
self::$all_cars[] = $this->name;
}
}
$bmw = new Car('bmw');
$benz = new Car('benz');
$tom = new Driver;
foreach (Car::$all_cars as $car) {
$tom->setRating($car, $rating); // $rating comes from user input
}
DriverclassDriverhave only onebmwor can they have any number of them?