如何使用 switch 语句优化多个 if-else 语句?

How can I optimize multiple if-else statements with a switch statement?

我正在编写代码以根据亚马逊、沃尔玛等渠道将评论电子邮件添加到队列中。我这样做的方式如下。我想知道是否可以通过其他方式优化代码,例如使用 Switch 或其他方式,这样我就不必使用多个 if-else 语句。

    if ($my_order->pay_method == AMAZONSTORE) {
        $emailQueue = new Luxe_EmailQueue();
        // $emailQueue->replace_or_add(EMAIL_REVIEW_MAIL1, $customerData->email, $subject, $body, $send_date_php, $my_order->id);
        // Temporary adding bcc
        $emailQueue->replace_or_add(EMAIL_REVIEW_MAIL1, $customerData->email, $subject, $body, $send_date_php, $my_order->id, null, "", "berkell990@gmail.com");
        $emailQueue->save();
        unset($emailQueue);

        // Add second (reminder) email also, for 7 days after the first email.
        $emailQueue = new Luxe_EmailQueue();
        // $emailQueue->replace_or_add(EMAIL_REVIEW_MAIL2, $customerData->email, $subject,
        // $smarty->fetch('amazon_store_review_email2.tpl'), $email_dispatch_dates['second_review_email_date_php'], $my_order->id);
        // Temporary adding bcc
        $emailQueue->replace_or_add(EMAIL_REVIEW_MAIL2, $customerData->email, $subject,
            $smarty->fetch('amazon_store_review_email2.tpl'), $email_dispatch_dates['second_review_email_date_php'], $my_order->id, null, "", "berkell990@gmail.com");
        $emailQueue->save();
        unset($emailQueue);
    } elseif ($my_order->pay_method == PMM) {
        # code...
    } elseif ($my_order->pay_method == RP) {
        # code...
    } elseif ($my_order->pay_method == WALMART) {
        # code...
    } elseif ($my_order->pay_method == EBAY) {
        # code...
    } else {
        // NO payment Method matched.
    }

Try This way

switch ($my_order->pay_method) {
  case "AMAZONSTORE":
    # code...
    break;
  case "PMM":
    # code...
    break;
  case "RP":
    # code...
    break;
  case "WALMART":
    # code...
    break;
  case "WALMART":
    # code...
    break;
  default:
    // NO payment Method matched.
}