Skip to content

PHP 对象继承

概述

继承是 OOP 的核心概念之一。PHP 使用 extends 关键字实现单继承,子类可以继承父类的属性和方法,并可重写或扩展它们。

版本要求

  • PHP 支持单继承(一个类只能 extends 一个父类)
  • 可同时使用 trait 实现代码复用

基础概念

extends 关键字

子类通过 extends 继承父类,获得父类所有 publicprotected 成员的访问权限。

php
<?php
declare(strict_types=1);

class Animal
{
    public string $name;
    protected int $age;

    public function __construct(string $name, int $age)
    {
        $this->name = $name;
        $this->age = $age;
    }

    public function speak(): string
    {
        return "{$this->name} makes a sound";
    }
}

class Dog extends Animal
{
    public function bark(): string
    {
        return "{$this->name} says Woof!";
    }

    public function speak(): string
    {
        return $this->bark();
    }
}

$dog = new Dog('Buddy', 3);
echo $dog->speak(); // Buddy says Woof!
echo $dog->name;    // Buddy

方法重写与 parent::

子类可以重写父类方法,使用 parent:: 调用父类的原始实现。

php
<?php
declare(strict_types=1);

class Shape
{
    public function __construct(
        protected int $x = 0,
        protected int $y = 0,
    ) {}

    public function describe(): string
    {
        return "Shape at ({$this->x}, {$this->y})";
    }
}

class Circle extends Shape
{
    public function __construct(
        int $x = 0,
        int $y = 0,
        protected int $radius = 1,
    ) {
        parent::__construct($x, $y);
    }

    public function describe(): string
    {
        return parent::describe() . " with radius {$this->radius}";
    }
}

$circle = new Circle(5, 10, 3);
echo $circle->describe(); // Shape at (5, 10) with radius 3

语法与代码

继承中的访问控制

php
<?php
declare(strict_types=1);

class ParentClass
{
    public string $publicVar = 'public';
    protected string $protectedVar = 'protected';
    private string $privateVar = 'private';
}

class ChildClass extends ParentClass
{
    public function show(): void
    {
        echo $this->publicVar;    // OK
        echo $this->protectedVar; // OK
        // echo $this->privateVar; // Fatal error
    }
}

签名兼容性规则

重写方法时必须遵循签名兼容性规则(里氏替换原则)。

php
<?php
declare(strict_types=1);

class Base
{
    public function process(int $a): string
    {
        return "Processed: {$a}";
    }
}

class ValidChild extends Base
{
    // OK: 必选 -> 可选(放宽)
    public function process(int $a = 10): string
    {
        return "Child processed: {$a}";
    }
}

继承链

php
<?php
declare(strict_types=1);

class A
{
    public function method(): string
    {
        return 'A';
    }
}

class B extends A
{
    public function method(): string
    {
        return parent::method() . ' -> B';
    }
}

class C extends B
{
    public function method(): string
    {
        return parent::method() . ' -> C';
    }
}

echo (new C())->method(); // A -> B -> C

详细说明

private 属性在子类中的行为

子类定义同名 private 属性时,实际创建了新的属性,与父类的 private 属性无关。

php
<?php
declare(strict_types=1);

class ParentCls
{
    private string $message = 'parent';
}

class ChildCls extends ParentCls
{
    private string $message = 'child';

    public function getChildMessage(): string
    {
        return $this->message; // 子类的 private
    }
}

$child = new ChildCls();
echo $child->getChildMessage(); // child

实战示例

抽象的 CRUD 基类

php
<?php
declare(strict_types=1);

abstract class BaseRepository
{
    public function __construct(
        protected readonly \PDO $db,
    ) {}

    public function findById(int $id): ?array
    {
        $table = $this->getTableName();
        $stmt = $this->db->prepare("SELECT * FROM {$table} WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(\PDO::FETCH_ASSOC) ?: null;
    }

    abstract protected function getTableName(): string;
}

class UserRepository extends BaseRepository
{
    protected function getTableName(): string
    {
        return 'users';
    }

    public function findByEmail(string $email): ?array
    {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        return $stmt->fetch(\PDO::FETCH_ASSOC) ?: null;
    }
}

注意事项

  1. PHP 不支持多继承:一个类只能 extends 一个父类
  2. parent:: 不限于构造函数:任何被重写的方法都可以调用
  3. 构造函数不受签名约束:子类构造函数可以完全不同
  4. 循环继承非法:A extends B extends A 会报错

最佳实践

  • 遵循里氏替换原则:子类应能替换父类而不破坏程序
  • 使用 parent:: 保持继承链:重写时调用父类方法
  • 抽象方法定义接口:强制子类实现特定功能
  • 组合优于继承:当关系不明确时优先使用组合

进阶用法

调试与测试技巧

php
<?php
declare(strict_types=1);

// 单元测试辅助函数
function createTestResource(): mixed
{
    return match (true) {
        default => new stdClass(),
    };
}

// 调试输出函数
function debugOutput(mixed , string  = ''): void
{
     =  ? ": " : '';
     .= print_r(, true);
    fwrite(STDERR,  . "\n");
}

// 性能基准测试
function benchmark(callable , int  = 1000): float
{
     = hrtime(true);
    for ($i = 0; $i < $iterations; $i++) {
        $fn();
    }
    return (hrtime(true) - $start) / 1e9;
}

日志记录实践

php
<?php
declare(strict_types=1);

/**
 * 简易日志记录器
 */
class SimpleLogger
{
    private string $logFile;
    private string $level = 'INFO';

    public function __construct(string $logFile)
    {
        $this->logFile = $logFile;
    }

    public function info(string $message, array $context = []): void
    {
        $this->log('INFO', $message, $context);
    }

    public function warning(string $message, array $context = []): void
    {
        $this->log('WARNING', $message, $context);
    }

    public function error(string $message, array $context = []): void
    {
        $this->log('ERROR', $message, $context);
    }

    private function log(string $level, string $message, array $context): void
    {
        $timestamp = date('Y-m-d H:i:s');
        $contextStr = $context ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
        $line = "[{$timestamp}] [{$level}] {$message}{$contextStr}\n";
        file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
    }
}

配置与环境检测

php
<?php
declare(strict_types=1);

// 环境检测工具
class EnvironmentChecker
{
    public static function checkRequirements(array $requirements): array
    {
        $results = [];
        foreach ($requirements as $name => $check) {
            $results[$name] = is_callable($check) ? $check() : false;
        }
        return $results;
    }

    public static function getSystemInfo(): array
    {
        return [
            'php_version' => PHP_VERSION,
            'os' => PHP_OS,
            'sapi' => PHP_SAPI,
            'memory_limit' => ini_get('memory_limit'),
            'max_execution_time' => ini_get('max_execution_time'),
            'loaded_extensions' => get_loaded_extensions(),
        ];
    }
}

常见问题排查

问题可能原因解决方案
连接超时网络问题/配置错误检查配置,增加超时时间
权限不足文件/目录权限使用 chmod/chown 修正
性能下降索引缺失/数据量大添加索引,优化查询
数据不一致并发冲突/事务残留使用锁机制和事务
内存溢出大数据集/未释放资源增大内存限制,分批处理

故障排除步骤

  1. 检查错误日志和异常信息
  2. 确认配置和环境是否正确
  3. 使用调试工具逐步排查
  4. 参考官方文档查找已知问题

版本兼容性说明

功能最低版本说明
基础功能PHP 8.1本文档基准版本
只读属性PHP 8.1public readonly 修饰符
枚举类型PHP 8.1enum 类型和 match 表达式
FiberPHP 8.1协程/轻量级并发
命名参数PHP 8.0foo(arg_name: value)
联合类型PHP 8.0`int
Null 安全运算符PHP 8.0$obj?->method()
析构器 promotionPHP 8.0__construct(public $x)
php
<?php
declare(strict_types=1);

// 版本兼容性检测
function ensureVersion(string $minVersion): void
{
    if (version_compare(PHP_VERSION, $minVersion, '<')) {
        throw new RuntimeException(
            sprintf('需要 PHP %s+, 当前版本: %s', $minVersion, PHP_VERSION)
        );
    }
}

ensureVersion('8.1.0');

参考链接