使用Abstract类而不包含PHP中的任何抽象方法

时间:2017-05-11 12:15:38

标签: php oop abstract-class

<?php
    ini_set('display_errors', "1");

    //create abstract method
    abstract class AbstractClass {

        public function getValue();

        // Common method
        public function printOut() {
        print $this->getValue() . "\n";
        }

    }

    //extend ConcreteClass1 with AbstractClass
    class ConcreteClass1 extends AbstractClass {

        public function getValue() {
        return "ConcreteClass1";
        }

        public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
        }

    }

    //extend ConcreteClass2 with AbstractClass
    class ConcreteClass2 extends AbstractClass {

        public function getValue() {
        return "ConcreteClass2";
        }

        public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass2";
        }

    }

    //create object of ConcreteClass1
    $class1 = new ConcreteClass1;
    $class1->printOut();
    echo $class1->getValue() . "\n";

    //create object of ConcreteClass2
    $class2 = new ConcreteClass2;
    $class2->printOut();
    echo $class2->getValue() . "\n";
?>

0 个答案:

没有答案