
前提
クラスを使ったことがなくその利便性が理解できません。
関数でできるのになぜ使うのかを知りたいです。
現状の関数
現状では次の関数apply_row()
を用いて、INSERT, DELETE, UPDATE などの処理をまとめています。
php
1// INSERT, DELETE, UPDATE の共通処理 2function apply_row( $type, $args ){ 3 $result = []; 4 5 // INSERT 6 if ( $type === 'insert' ) { 7 $result = insert_row( $args ); 8 9 // DELETE 10 } else if ( $type === 'delete' ) { 11 $result = delete_row( $args ); 12 13 // UPDATE 14 } else if ( $type === 'update' ) { 15 $result = update_row( $args ); 16 } 17 18 return $result; 19} 20 21// INSERT 22function insert_row( $args ){ 23 $sql = "INSERT INTO tbl (name, age) VALUES ($args['name'], $args['age']);"; 24} 25 26// DELETE 27function delete_row( $args ){ 28 29} 30 31// UPDATE 32function update_row( $args ){ 33 34} 35 36// INSERTを実行 37$args = ['name'=>'a','age'=>20]; 38$result = apply_row( 'insert', $args );
試したクラス
上記の関数に対し、ある方から「クラスを使うべし」とアドバイスを頂きました。
そこで初めてクラスを調べ、上記関数と同じ動作を実現するクラスを書けたかと思います。
php
1// INSERT, DELETE, UPDATE の共通処理 2class apply_row { 3 public $id; 4 public $name; 5 public $age; 6 7 public function __construct( $args ) { 8 $this->name = $args['name']; 9 $this->id = $args['id']; 10 $this->age = $args['age']; 11 } 12} 13 14// INSERT 15class insert_row extends apply_row { 16 public function apply(){ 17 $sql = "INSERT INTO tbl (name, age) VALUES ({$this->name}, {$this->age});"; 18 } 19} 20 21// DELETE 22class delete_row extends apply_row { 23 public function apply(){ 24 25 } 26} 27 28// UPDATE 29class update_row extends apply_row { 30 public function apply(){ 31 32 } 33} 34 35// INSERTを実行 36$args = ['name'=>'a','age'=>20]; 37$insert_row = new insert_row( $args ); 38$insert_row->apply();
ですが、こうしてクラスを使うと何が便利なのか、よくわかりません。
クラスの利便性とはどのようなものなのでしょうか?
また、現状私のアプリケーションは全て関数で構成されているのですが、上のようにすべてクラスに置き換えた方がいいのでしょうか?

回答6件
あなたの回答
tips
プレビュー