继承 #

一、继承基础 #

1.1 基本语法 #

php
<?php
class Animal
{
    public string $name;
    
    public function __construct(string $name)
    {
        $this->name = $name;
    }
    
    public function speak(): string
    {
        return "Some sound";
    }
}

class Dog extends Animal
{
    public function speak(): string
    {
        return "Woof!";
    }
}

$dog = new Dog("Buddy");
echo $dog->name;
echo $dog->speak();

1.2 方法重写 #

php
<?php
class ParentClass
{
    public function greet(): string
    {
        return "Hello from parent";
    }
}

class ChildClass extends ParentClass
{
    public function greet(): string
    {
        return "Hello from child";
    }
}

1.3 调用父类方法 #

php
<?php
class ParentClass
{
    public function greet(): string
    {
        return "Hello";
    }
}

class ChildClass extends ParentClass
{
    public function greet(): string
    {
        return parent::greet() . " from child";
    }
}

二、final关键字 #

2.1 阻止继承 #

php
<?php
final class Utility
{
}

class MyUtility extends Utility
{
}

2.2 阻止重写 #

php
<?php
class Base
{
    final public function criticalMethod(): void
    {
    }
}

class Derived extends Base
{
    public function criticalMethod(): void
    {
    }
}

三、抽象类 #

php
<?php
abstract class Shape
{
    abstract public function area(): float;
    
    public function describe(): string
    {
        return "Area: " . $this->area();
    }
}

class Rectangle extends Shape
{
    public function __construct(
        private float $width,
        private float $height
    ) {}
    
    public function area(): float
    {
        return $this->width * $this->height;
    }
}

四、接口 #

php
<?php
interface Flyable
{
    public function fly(): string;
}

interface Swimmable
{
    public function swim(): string;
}

class Duck implements Flyable, Swimmable
{
    public function fly(): string
    {
        return "Flying";
    }
    
    public function swim(): string
    {
        return "Swimming";
    }
}

五、总结 #

本章学习了:

  • extends继承
  • 方法重写
  • parent调用
  • final关键字
  • 抽象类
  • 接口

下一章将学习Trait。

最后更新:2026-03-26