Created
December 20, 2015 02:44
-
-
Save bzz0217/50c623bff6f9f610fc70 to your computer and use it in GitHub Desktop.
template_method.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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