两个字段都等于空值,无法显示错误消息

时间:2012-10-12 22:00:31

标签: php

我正在开发预订系统,客户最多可以预订3个座位。如果他们只预订1个座位,这意味着其他2个座位值设置为空,当我提交表格时,我会检查它以确保客户不会尝试双重预订相同的座位,正如您将在下面的代码,所以如果客户购买1个座位,他们会收到错误,因为两个座位都等于null,我该如何解决?谢谢

if($seat1==$seat2 || $seat2==$seat3 || $seat1==$seat3){
echo("You're trying to book the same seat numerous times, please go back.");
die();
}

2 个答案:

答案 0 :(得分:1)

使用数组。他们可以拥有任意数量的值,所以你不会有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,它将变得复杂两倍

答案 1 :(得分:0)

这是明显的答案,我会让别人浮华和嗖嗖:)

if ( $seat1 === $seat2 || $seat1 === $seat3 || ($seat2 !== null && $seat2 === $seat3) )