[php] interface, abstract
#1
<?php
interface ContractInterface {
public function promiseMethod(array $param): int;
}
class ConcreateClass implements ContractInterface {
public function promiseMethod(array $param): int {
$result = 0;
foreach ($param as $element) {
$result += $element;
}
return $result;
}
}
$arr = array(1, 2, 3);
$obj = new ConcreateClass();
$result = $obj->promiseMethod($arr);
echo $result;
#2
<?php
abstract class ParentClass {
public function a() {
echo 'a';
}
public abstract function b();
}
class ChildClass extends ParentClass {
public function b() {
echo 'hi~';
}
}
$obj = new ChildClass();
$obj->b();
#3 template method 패턴
<?php
abstract class AbstractPageTemplate {
protected abstract function header();
protected abstract function article();
protected abstract function footer();
protected final function template() {
$result = $this->header();
$result .= $this->article();
$result .= $this->footer();
return $result;
}
public function render() {
return $this->template();
}
}
class TextPage extends AbstractPageTemplate {
protected function header() {
return "PHP\n";
}
protected function article() {
return "PHP: HyperText Preprocessor\n";
}
protected function footer() {
return "website is php.net\n";
}
}
class HtmlPage extends AbstractPageTemplate {
protected function header() {
return "<header>PHP</header>\n";
}
protected function article() {
return "<article>PHP: HyperText Preprocessor</article>\n";
}
protected function footer() {
return "<footer>website is php.net</footer>\n";
}
public function render() {
$result = '<html>';
$result .= $this->template();
$result .= '</html>';
return $result;
}
}
$text = new TextPage();
echo $text->render();
$html = new HtmlPage();
echo $html->render();
- Thanks to 생활코딩
Author And Source
이 문제에 관하여([php] interface, abstract), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@devyang97/php-interface-abstract저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)