■サンプル
では実際にクラスを使ったサンプルを作成してみましょう。
form.html
※bootstrapを使用しています
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | <! DOCTYPE html> < html > < head > < meta charset = "UTF-8" > < title >ユーザー登録</ title > < link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" > </ head > < body > < div class = "container" > < div class = "h1 mt-5 mb-5" >ユーザー登録</ div > < form action = "process.php" method = "POST" > < div class = "form-group row" > < label for = "name" class = "col-sm-2 col-form-label" >お名前</ label > < div class = "col-sm-8" > < input type = "text" class = "form-control form-control-lg" name = "name" id = "name" placeholder = "お名前" > </ div > </ div > < div class = "form-group row" > < label for = "email" class = "col-sm-2 col-form-label" >メールアドレス</ label > < div class = "col-sm-8" > < input type = "text" class = "form-control form-control-lg" name = "email" id = "email" placeholder = "メールアドレス" > </ div > </ div > < div class = "form-group row" > < label for = "password" class = "col-sm-2 col-form-label" >パスワード</ label > < div class = "col-sm-8" > < input type = "password" class = "form-control form-control-lg" name = "password" id = "password" placeholder = "パスワード" > </ div > </ div > < div class = "form-group row" > < div class = "col-sm-5 offset-2" > < button type = "submit" class = "btn btn-primary" >登 録</ button > </ div > </ div > </ form > </ div > </ body > </ html > |
InputForm.php
form.htmlを想定したクラスです。
入力フォームがプロパティとなっております。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <?php class InputForm { private $name ; private $email ; private $password ; public function setName( $name ) { $this ->name = $name ; } public function getName() { return $this ->name; } public function setEmail( $email ) { $this ->email = $email ; } public function getEmail() { return $this ->email; } public function setPassword( $password ) { $this ->password = $password ; } public function getPassword() { return $this ->password; } } ?> |
process.php
入力された値をインスタンスのプロパティにセットし、最終的には表示しています。
その際に、クラスに定義したメソッドを使用しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php require 'InputForm.php' ; $form = new InputForm(); $form ->setName( $_POST [ 'name' ]); $form ->setEmail( $_POST [ 'email' ]); $form ->setPassword( $_POST [ 'password' ]); print ( '名前 : ' . $form ->getName()); print ( '<br>' ); print ( 'メールアドレス : ' . $form ->getEmail()); print ( '<br>' ); print ( 'パスワード : ' . $form ->getPassword()); ?> |
入力した結果が表示されます。
■まとめ
画面に入力された値をPHP側で表示するだけなら、もっと簡単に書くことはできます。
しかし、入力フォーム画面をオブジェクトとして捉えると上記のような書き方になります。
ただ表示するだけのサンプルにはなっておりますが、実際にはバリデーションチェックをしたり、データベースに登録したりと複雑な後続処理が続きます。
複雑な処理がたくさん行われる場合はオブジェクト指向で書いていると、実際の感覚と同じようにデータを扱えるため、考えを整理しやすくなります。