使用数组。它们可以具有任意数量的值,因此您没有 3 的限制,尽管您仍然可以强制执行它。当你使用它时,你也可以使用一个类。就是图个好玩儿。;)
$mrA = new User("GolezTrol");
$mrB = new User("user1715417");
try {
$booking = new Booking();
$booking->bookSeat($mrA, 'A7');
$booking->bookSeat($mrA, 'A8');
// $booking->bookSeat($mrB, 'A8'); // Double booking
$booking->bookSeat($mrB, 'A9');
$booking->bookSeat($mrA, 'B7');
// $booking->bookSeat($mrA, 'B8'); // Only 3 seats allowed per user
$booking->bookSeat($mrB, 'B9');
// $booking->bookSeat($mrB, 'C7'); // No Seat Left
var_dump($booking->bookedSeats); // Output Booking
} catch ( Exception $e ) {
echo $e->getMessage(), PHP_EOL;
}
输出
array
'GolezTrol' =>
array
0 => string 'A7' (length=2)
1 => string 'A8' (length=2)
2 => string 'B7' (length=2)
'user1715417' =>
array
0 => string 'A9' (length=2)
1 => string 'B9' (length=2)
使用的类
class User {
public $id;
function __construct($id) {
$this->id = $id;
}
function __toString() {
return $this->id;
}
}
class Booking {
public $bookedSeats = array();
public $seatUsed = array();
private $maxSeat = 5;
private $maxBooking = 3;
public function bookSeat(User $user, $seat) {
if (count($this->seatUsed) >= $this->maxSeat) {
throw new Exception('No Seat Left');
}
if (in_array($seat, $this->seatUsed)) {
throw new Exception('Double booking');
}
if (array_key_exists($user->id, $this->bookedSeats)) {
if (count($this->bookedSeats[$user->id]) >= $this->maxBooking) {
throw new Exception('Only 3 seats allowed');
}
$this->bookedSeats[$user->id][] = $seat;
$this->seatUsed[] = $seat;
} else {
$this->bookedSeats[$user->id] = array();
$this->bookedSeats[$user->id][] = $seat;
$this->seatUsed[] = $seat;
}
}
}
您可以看到将限制设置为 5 或 8 个席位是多么容易,而无需修改除数字之外的任何内容,而您当前的检查已经很复杂,如果您从 3 增加到 5,它将变得复杂两倍。