2
我有什麼:PHP - 讓類對象作爲屬性另一類
$tom = new Driver;
$bmw = new Car;
$benz = new Car;
我想擁有什麼:
foreach (Car::$all_cars as $car) {
$tom->setRating($car, $rating); // $rating comes from user input
}
問:
如何實施這個?
約束:
- 車對象的數量是可變的和未知的(因此沒有靜態屬性在驅動程序類名)。
- 每個車手對於車類中的每個物品都有評分。
- 評級屬性應在驅動程序類別中有意定義。
我想什麼:
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
}
創建汽車的數組給了代碼工作的例子 –
一個'Driver'只能有一個'bmw'或者他們可以擁有任意數量的他們? – Tigger