LoginSignup
25
25

More than 5 years have passed since last update.

try~catch使うほどじゃないけどgotoは嫌だってときのための便利な書き方

Posted at

目的

「まとめて例外をスローする小技」 では何だか大がかり過ぎるなぁ、もっとライトなソリューションが欲しいなぁ、って時に(適当)

入力フォームと実行スクリプトが別ファイルのとき

while (true) { ... } のように末尾に break を必要としない書き方です。

<?php

// ※
function h($str) {
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}

// ※
foreach (['name', 'email', 'comment'] as $v) {
    $$v = (string)filter_input(INPUT_POST, $v);
}

do {

    // 入力項目チェック
    if ($name === '') {
        $msgs[] = '名前が未入力';
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $msgs[] = 'Eメールが未入力または無効';
    }
    if ($comment === '') {
        $msgs[] = 'コメントが未入力';
    }

    // 1つでもエラーが発生していればdoブロックを脱出
    if (!empty($msgs)) {
        break;
    }

    // 処理を実行
    do_something_action($name, $email, $comment);
    $msgs[] = '~実行完了しました';

} while (false);

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

?>
<!DOCTYPE html>
<html>
<body>
<?php if (!empty($msgs)): ?>
  <ul>
<?php foreach ($msgs as $msg): ?>
    <li><?=h($msg)?></li>
<?php endforeach; ?>
  </ul>
<?php endif; ?>
</body>
</html>

入力フォームと実行スクリプトが同一ファイルのとき

doif 組み合わせられるのってPHP特有なんですかね…?

<?php

// ※
function h($str) {
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}

// ※
foreach (['name', 'email', 'comment'] as $v) {
    $$v = (string)filter_input(INPUT_POST, $v);
}

// 何かPOSTデータがあったときだけ実行
do if ($_POST) {

    // 入力項目チェック
    if ($name === '') {
        $msgs[] = '名前が未入力';
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $msgs[] = 'Eメールが未入力または無効';
    }
    if ($comment === '') {
        $msgs[] = 'コメントが未入力';
    }

    // 1つでもエラーが発生していればdoブロックを脱出
    if (!empty($msgs)) {
        break;
    }

    // 処理を実行
    do_something_action($name, $email, $comment);
    $msgs[] = '~実行完了しました';

    // フォームをクリア
    $name = $email = $comment = '';

} while (false);

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

?>
<!DOCTYPE html>
<html>
<body>
<?php if (!empty($msgs)): ?>
  <ul>
<?php foreach ($msgs as $msg): ?>
    <li><?=h($msg)?></li>
<?php endforeach; ?>
  </ul>
<?php endif; ?>
  <form method="post" action="">
    名前: <input type="text" name="name" value="<?=h($name)?>"><br>
    Eメール: <input type="text" name="email" value="<?=h($email)?>"><br>
    コメント: <input type="text" name="comment" value="<?=h($comment)?>"><br>
    <input type="submit" value="送信">
  </form>
</body>
</html>
25
25
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
25