[php] interface, abstract

15402 단어 phpphp

#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 생활코딩

좋은 웹페이지 즐겨찾기