批改状态:未批改
老师批语:
1、抽象类与接口
抽象类:在类中定义一些方法和属性,不具体实现,实现的功能通过子类去实现。抽象类只作为一个模板。在类中只要有一个方法为抽象方法,此类就是抽象类。
接口:高于抽象类,接口中没有实现的方法,所有的方法都为抽象,并且所有的属性都为public。是类的模板。抽象类介于接口和类之间,是一个过度。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<?php
// 抽象类
abstract class Person{
protected $name;
public function __construct($name="xiao wang"){
$this->name = $name;
}
public function getName(){
return $this->name;
}
abstract protected function setName($value);
}
//抽象类不可以实例化,只能被继承
class Stu extends Person{
public function __construct($name = "xiaowang"){
parent::__construct($name);
}
//子类中必须要实现父类中的抽象方法
public function setName($value){
$this->name = $value;
}
}
$stu = new Stu('小王');
echo '类中的名字为'.$stu->getName().'<br>';
$stu->setName('小李');
echo '类中重新设置的名字为'.$stu->getName().'<br>';
echo "***************************************************************************<br>";
//接口
interface iVehicle{
//所有的方法都为抽象的,可以不用写abstract
public function setFuel($fule);
public function setPurpose($purpose);
}
class Car implements iVehicle{
public $fule;
public $purpose;
public function __construct($fule = '汽油',$purpose = '家用'){
$this->fule = $fule;
$this->purpose = $purpose;
}
public function setFuel($fule){
$this->fuel = $fule;
}
public function setPurpose($purpose){
$this->purpose = $purpose;
}
//在类中除了要实现接口中的方法外,还可以添加自己的方法
public function getInfo(){
return $this->fule.$this->purpose.'车<br>';
}
}
$car = new Car();
echo $car->getInfo();
$car->setFuel('新能源');
$car->setPurpose('公交');
echo $car->getInfo();
echo '<hr>';
?>
</body>
</html>点击 "运行实例" 按钮查看在线实例

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号