추상 클래스 및 인터페이스로그인

추상 클래스 및 인터페이스

PHP에서는 추상 키워드를 통해 추상 클래스를 선언할 수 있습니다. 때로는 특정 공개 메서드를 포함하는 클래스가 필요할 때도 있습니다. 이 경우 인터페이스 기술을 사용하여

1 동물 클래스를 만들 수 있습니다.

Animal.class.php 코드는 다음과 같습니다.

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/3 0003
 * Time: 下午 2:13
 */
abstract class Animal{
    public $gender;  //性别
    public $size;      //尺寸
    public function __construct($gender,$size){
        $this->gender=$gender;
        $this->size=$size;
    }
    //限制非抽象类都需要调用此方法
    abstract protected function getGender();
    //final要求每个子类必须存在该方法并且不能重写
    final public function getSize(){
        return $this->size;
    }
}

2. 강아지 클래스를 생성합니다.

Dog.class.php 코드는 다음과 같습니다.

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/3 0003
 * Time: 下午 2:20
 */
header('content-type:text/html;charset=utf8');
require './Animal.class.php';
class Dog extends Animal {
    /**
     * @return mixed
     */
    public function getGender()
    {
        return "'$this->gender'狗";
    }
}
$dog=new Dog('公','大');
echo $dog->getSize();
echo $dog->getGender();

실행 결과는 다음과 같습니다.

微信图片_20180303144604.png

3 4, 인터페이스 클래스 호출

interface.php 파일을 생성합니다. 코드는 다음과 같습니다.

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/3 0003
 * Time: 下午 2:22
 */
header('content-type:text/html;charset=utf8');
require './Animal.class.php';
class Cat extends Animal { 
    public function getGender()
    {
        return "'$this->gender'猫";
    }
}
$dog=new Cat('母','小');
echo $dog->getSize();
echo $dog->getGender();

실행 결과 :

微信图片_20180303144607.png

다음 섹션
<?php echo '抽象类与接口的使用'; >
코스웨어