首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 實現簡易計算器:表單處理、Switch 分支與 Session 狀態保持

     編輯:PHP 綜合知識

簡易計算器是 PHP 表單處理、條件分支、狀態管理的經典入門專案。本文提供完整單檔案實現,涵蓋 HTML 表單、後端運算、結果顯示與 Session 保持。

完整單檔案實現 calculator.php

<?php
session_start();
header('Content-Type: text/html; charset=utf-8');

// 處理表單提交
$result = null;
$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $num1 = isset($_POST['num1']) ? (float)$_POST['num1'] : null;
    $num2 = isset($_POST['num2']) ? (float)$_POST['num2'] : null;
    $oper = $_POST['oper'] ?? '';
    
    if ($num1 === null || $num2 === null) {
        $error = '請輸入有效數字';
    } elseif (!in_array($oper, ['+', '-', '*', '/'])) {
        $error = '無效運算符';
    } else {
        switch ($oper) {
            case '+': $result = $num1 + $num2; break;
            case '-': $result = $num1 - $num2; break;
            case '*': $result = $num1 * $num2; break;
            case '/': 
                if ($num2 == 0) {
                    $error = '除數不能為零';
                } else {
                    $result = $num1 / $num2;
                }
                break;
        }
    }
    
    // 保存結果到 Session (可選)
    if ($result !== null) {
        $_SESSION['last_result'] = $result;
        $_SESSION['last_expr'] = "$num1 $oper $num2 = $result";
    }
}
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>PHP 簡易計算器</title>
    <style>
        body { font-family: sans-serif; max-width: 400px; margin: 2rem auto; }
        .form-group { margin-bottom: 1rem; }
        label { display: inline-block; width: 80px; }
        input, select { padding: 0.5rem; }
        .result { padding: 1rem; background: #f0f0f0; margin-top: 1rem; }
        .error { color: red; }
        .history { font-size: 0.9em; color: #666; margin-top: 1rem; }
    </style>
</head>
<body>
    <h1>簡易計算器</h1>
    <form method="POST">
        <div class="form-group">
            <label>第一個數</label>
            <input type="number" step="any" name="num1" required value="<?= htmlspecialchars($_POST['num1'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>運算符號</label>
            <select name="oper">
                <option value="+" <?= ($_POST['oper'] ?? '') === '+' ? 'selected' : '' ?>>+</option>
                <option value="-" <?= ($_POST['oper'] ?? '') === '-' ? 'selected' : '' ?>>-</option>
                <option value="*" <?= ($_POST['oper'] ?? '') === '*' ? 'selected' : '' ?>>×</option>
                <option value="/" <?= ($_POST['oper'] ?? '') === '/' ? 'selected' : '' ?>>÷</option>
            </select>
        </div>
        <div class="form-group">
            <label>第二個數</label>
            <input type="number" step="any" name="num2" required value="<?= htmlspecialchars($_POST['num2'] ?? '') ?>">
        </div>
        <button type="submit">計算結果</button>
    </form>
    
    <?php if ($error): ?>
        <div class="error"><?= $error ?></div>
    <?php elseif ($result !== null): ?>
        <div class="result">
            <strong>結果:</strong> <?= $result ?>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['last_expr'])): ?>
        <div class="history">上次計算:<?= $_SESSION['last_expr'] ?></div>
    <?php endif; ?>
</body></html>

關鍵知識點解析

概念代碼體現說明
表單提交$_SERVER['REQUEST_METHOD'] === 'POST'區分 GET 顯示與 POST 提交
輸入驗證(float)$_POST['num1'] + 空值檢查類型轉換與業務驗證分離
Switch 分支switch($oper)離散值多路分支最佳選擇
除零保護if ($num2 == 0)業務邊界條件必須顯式處理
XSS 防護htmlspecialchars() 輸出轉義所有動態輸出必須轉義
狀態保持$_SESSION['last_result']跨請求共享資料
表單回填value=""提升用戶體驗

進階擴展方向

  1. 歷史記錄:陣列存儲 $_SESSION['history'][] = $expr,顯示最近 10 筆
  2. 科學運算:擴展運算符 %、**、sqrt、pow
  3. AJAX 無刷新:fetch() 發送 JSON,返回 {result: 100}
  4. 單元測試:提取 calculate($a, $op, $b) 純函數,PHPUnit 測試
  5. 錯誤日誌:error_log() 記錄異常輸入與系統錯誤

架構改進建議

隨著功能增長,建議採用 MVC 分層:

  • Model:Calculator 類封裝運算邏輯
  • View:獨立模板檔案 calculator.phtml
  • Controller:路由分發、請求處理、回應構建

這個簡單專案蘊含了 Web 開發的核心要素:輸入→處理→輸出、狀態管理、安全防護、用戶體驗,是新手邁向實戰的最佳練習。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved