类与对象 #

一、面向对象概述 #

1.1 什么是面向对象 #

面向对象编程(OOP)是一种编程范式,将数据和操作数据的方法封装在对象中。

1.2 核心概念 #

  • 类(Class):对象的模板
  • 对象(Object):类的实例
  • 属性(Property):对象的数据
  • 方法(Method):对象的行为

二、类的定义 #

2.1 基本语法 #

php
<?php
class User
{
    public string $name;
    public int $age;
    
    public function greet(): string
    {
        return "Hello, I'm {$this->name}";
    }
}

2.2 创建对象 #

php
<?php
$user = new User();
$user->name = "John";
$user->age = 25;

echo $user->greet();

2.3 类型化属性(PHP 7.4+) #

php
<?php
class Product
{
    public int $id;
    public string $name;
    public float $price;
    public bool $available = true;
    public ?string $description = null;
}

2.4 只读属性(PHP 8.1+) #

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

$user = new User(1, "John");
$user->name = "Jane";

三、属性 #

3.1 访问修饰符 #

php
<?php
class User
{
    public string $name;
    protected int $age;
    private string $email;
}
修饰符 类内部 子类 外部
public
protected
private

3.2 默认值 #

php
<?php
class Config
{
    public string $env = 'development';
    public bool $debug = false;
    public array $cache = [];
}

3.3 静态属性 #

php
<?php
class Counter
{
    public static int $count = 0;
    
    public static function increment(): int
    {
        return ++self::$count;
    }
}

echo Counter::$count;
Counter::$count = 10;
echo Counter::increment();

3.4 常量 #

php
<?php
class User
{
    public const STATUS_ACTIVE = 1;
    public const STATUS_INACTIVE = 0;
    
    public static function getActiveStatus(): int
    {
        return self::STATUS_ACTIVE;
    }
}

echo User::STATUS_ACTIVE;

四、方法 #

4.1 定义方法 #

php
<?php
class Calculator
{
    public function add(int $a, int $b): int
    {
        return $a + $b;
    }
    
    private function validate(int $value): bool
    {
        return $value >= 0;
    }
}

4.2 调用方法 #

php
<?php
$calc = new Calculator();
echo $calc->add(1, 2);

4.3 静态方法 #

php
<?php
class Math
{
    public static function square(int $n): int
    {
        return $n * $n;
    }
}

echo Math::square(5);

4.4 类型声明 #

php
<?php
class UserService
{
    public function find(int $id): ?User
    {
        return $this->repository->find($id);
    }
    
    public function create(array $data): User
    {
        return new User($data);
    }
}

五、$this关键字 #

5.1 访问属性 #

php
<?php
class User
{
    public string $name;
    
    public function getName(): string
    {
        return $this->name;
    }
    
    public function setName(string $name): void
    {
        $this->name = $name;
    }
}

5.2 调用方法 #

php
<?php
class User
{
    public function validate(): bool
    {
        return $this->isValidEmail() && $this->isValidName();
    }
    
    private function isValidEmail(): bool
    {
        return true;
    }
    
    private function isValidName(): bool
    {
        return true;
    }
}

六、对象操作 #

6.1 克隆对象 #

php
<?php
$user1 = new User();
$user1->name = "John";

$user2 = clone $user1;
$user2->name = "Jane";

echo $user1->name;
echo $user2->name;

6.2 比较对象 #

php
<?php
$user1 = new User();
$user2 = new User();
$user3 = $user1;

var_dump($user1 == $user2);
var_dump($user1 === $user2);
var_dump($user1 === $user3);

6.3 检查类型 #

php
<?php
$user = new User();

if ($user instanceof User) {
    echo "Is a User";
}

6.4 获取类名 #

php
<?php
$user = new User();

echo get_class($user);
echo User::class;

七、实际应用 #

7.1 实体类 #

php
<?php
class User
{
    public function __construct(
        public readonly int $id,
        public string $name,
        public string $email,
        public readonly DateTime $createdAt
    ) {}
    
    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->createdAt->format('Y-m-d H:i:s')
        ];
    }
}

7.2 服务类 #

php
<?php
class UserService
{
    private array $users = [];
    
    public function create(array $data): User
    {
        $user = new User(
            $this->generateId(),
            $data['name'],
            $data['email'],
            new DateTime()
        );
        
        $this->users[$user->id] = $user;
        return $user;
    }
    
    public function find(int $id): ?User
    {
        return $this->users[$id] ?? null;
    }
    
    private function generateId(): int
    {
        return count($this->users) + 1;
    }
}

八、总结 #

本章学习了:

  • 类的定义
  • 对象的创建
  • 属性和访问修饰符
  • 方法的定义
  • $this关键字
  • 对象操作

下一章将学习构造与析构函数。

最后更新:2026-03-26