What is an abstract class in PHP?

前端 未结 6 499
萌比男神i
萌比男神i 2020-11-30 18:08

What is an abstract class in PHP?

How can it be used?

6条回答
  •  孤独总比滥情好
    2020-11-30 18:34

    Abstract Class
    1. Contains an abstract method
    2. Cannot be directly initialized
    3. Cannot create an object of abstract class
    4. Only used for inheritance purposes

    Abstract Method
    1. Cannot contain a body
    2. Cannot be defined as private
    3. Child classes must define the methods declared in abstract class

    Example Code:

    abstract class A {
        public function test1() {
            echo 'Hello World';
        }
        abstract protected function f1();
        abstract public function f2();
        protected function test2(){
            echo 'Hello World test';
        }
    }
    
    class B extends A {
        public $a = 'India';
        public function f1() {
            echo "F1 Method Call";
        }
        public function f2() {
            echo "F2 Method Call";
        }
    }
    
    $b = new B();
    echo $b->test1() . "
    "; echo $b->a . "
    "; echo $b->test2() . "
    "; echo $b->f1() . "
    "; echo $b->f2() . "
    ";

    Output:

    Hello World
    India
    Hello World test
    F1 Method Call
    F2 Method Call
    

提交回复
热议问题