构造与析构 #

一、构造函数 #

1.1 基本语法 #

php
<?php
class User
{
    public string $name;
    public int $age;
    
    public function __construct(string $name, int $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
}

$user = new User("John", 25);
echo $user->name;

1.2 构造函数提升(PHP 8.0+) #

php
<?php
class User
{
    public function __construct(
        public string $name,
        public int $age
    ) {}
}

$user = new User("John", 25);
echo $user->name;

1.3 默认参数 #

php
<?php
class Config
{
    public function __construct(
        public string $env = 'development',
        public bool $debug = false
    ) {}
}

$config = new Config();
$config = new Config('production', true);

1.4 类型声明 #

php
<?php
class Order
{
    public function __construct(
        public readonly int $id,
        public readonly User $user,
        public readonly array $items,
        public readonly DateTime $createdAt = new DateTime()
    ) {}
}

二、析构函数 #

2.1 基本语法 #

php
<?php
class FileHandler
{
    private $handle;
    
    public function __construct(string $path)
    {
        $this->handle = fopen($path, 'r');
    }
    
    public function __destruct()
    {
        if ($this->handle) {
            fclose($this->handle);
        }
    }
}

2.2 手动触发 #

php
<?php
$handler = new FileHandler('data.txt');
unset($handler);

三、构造函数特性 #

3.1 调用父类构造函数 #

php
<?php
class ParentClass
{
    public function __construct(string $name)
    {
        echo "Parent: $name\n";
    }
}

class ChildClass extends ParentClass
{
    public function __construct(string $name, int $age)
    {
        parent::__construct($name);
        echo "Child: $age\n";
    }
}

3.2 私有构造函数(单例模式) #

php
<?php
class Singleton
{
    private static ?Singleton $instance = null;
    
    private function __construct()
    {
    }
    
    public static function getInstance(): Singleton
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __clone()
    {
    }
}

$instance = Singleton::getInstance();

3.3 命名参数(PHP 8.0+) #

php
<?php
class User
{
    public function __construct(
        public string $name,
        public int $age,
        public string $city = 'Beijing'
    ) {}
}

$user = new User(
    age: 25,
    name: "John"
);

四、实际应用 #

4.1 依赖注入 #

php
<?php
class UserService
{
    public function __construct(
        private UserRepository $repository,
        private LoggerInterface $logger
    ) {}
    
    public function find(int $id): ?User
    {
        $this->logger->log("Finding user: $id");
        return $this->repository->find($id);
    }
}

4.2 数据库连接 #

php
<?php
class Database
{
    private PDO $connection;
    
    public function __construct(
        string $host,
        string $database,
        string $username,
        string $password
    ) {
        $dsn = "mysql:host=$host;dbname=$database;charset=utf8mb4";
        $this->connection = new PDO($dsn, $username, $password);
    }
    
    public function getConnection(): PDO
    {
        return $this->connection;
    }
    
    public function __destruct()
    {
        $this->connection = null;
    }
}

五、总结 #

本章学习了:

  • 构造函数__construct
  • 析构函数__destruct
  • 构造函数提升
  • 父类构造函数调用
  • 单例模式

下一章将学习访问控制。

最后更新:2026-03-26