Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bzz0217/50c623bff6f9f610fc70 to your computer and use it in GitHub Desktop.
Save bzz0217/50c623bff6f9f610fc70 to your computer and use it in GitHub Desktop.
template_method.php
<?php
//Template Methodパターン
abstract class test {
//継承先で必ず実装が必要なメソッド
abstract function main();
private $num = 0;
protected function plus($a, $b){
return $this->num = $a + $b;
}
protected function minus($a, $b){
return $this->num = $a - $b;
}
protected function get_num(){
echo $this->num . "<br>";
}
}
class test2 extends test {
public function main(){
$res = $this->plus(10, 1);
echo $res . "<br>"; //11
$res = $this->minus(10, 1);
echo $res . "<br>"; //9
//親クラスのnumプロパティの出力
echo $this->get_num(); //9
//子クラスにnumプロパティが生成される
//ない場合、自動生成されるのでバグ注意
$this->num = 5;
echo $this->num . "<br>"; //5
//親クラスのプロパティを出力
echo $this->get_num() . "<br>"; //9
}
}
$t = new test2();
$res = $t->main();
var_dump($t);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment