首页 / PHP 入门教程 / PHP 面向对象基础

PHP 入门教程

PHP 面向对象基础

本教程共 65 篇 · 第 19 篇 · 更新于 2026-07-24 · 约 4 分钟阅读

PHPPHP8面向对象对象属性方法封装

19. PHP 面向对象基础

本节目标:掌握类、对象、属性和方法的基础知识。学完你能用面向对象方式组织代码,创建可复用的模块。

19.1 类与对象

是对象的模板,对象是类的实例:

<?php
// 定义一个类
class Car {
    // 属性
    public string $brand;
    public string $color;
    
    // 方法
    public function drive(): string {
        return "{$this->color}的{$this->brand}在行驶";
    }
}

// 创建对象(实例化)
$myCar = new Car();
$myCar->brand = "丰田";
$myCar->color = "白色";

echo $myCar->drive();  // 白色的丰田在行驶

// PHP 8.0+ 构造函数属性提升(更简洁)
class Car2 {
    public function __construct(
        public string $brand,
        public string $color
    ) {}
    
    public function drive(): string {
        return "{$this->color}的{$this->brand}在行驶";
    }
}

$car2 = new Car2("本田", "红色");
echo $car2->drive();  // 红色的本田在行驶
?>
Tip

PHP 8.0 的构造函数属性提升可以大幅减少重复代码。推荐在新项目中使用。

19.2 属性访问控制

<?php
class BankAccount {
    // public:任何地方可访问
    public string $owner;
    
    // private:仅类内部可访问
    private float $balance = 0;
    
    // protected:类内部和子类可访问
    protected string $accountType = "储蓄";
    
    public function deposit(float $amount): void {
        if ($amount > 0) {
            $this->balance += $amount;
        }
    }
    
    public function getBalance(): float {
        return $this->balance;
    }
}

$account = new BankAccount();
$account->owner = "张三";
$account->deposit(1000);
echo $account->getBalance();  // 1000

// $account->balance = 999999;  // 错误!private 属性不能外部访问
?>
修饰符类内部子类外部
public
protected
private
Note

属性应尽可能声明为 privateprotected,通过方法控制访问。这称为封装

19.3 构造函数和析构函数

构造函数 __construct()

对象创建时自动调用:

<?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("张三", 25);
echo $user->name;  // 张三
?>

析构函数 __destruct()

对象被销毁前自动调用:

<?php
class FileHandler {
    private $handle;
    
    public function __construct(string $filename) {
        $this->handle = fopen($filename, 'r');
        echo "文件已打开\n";
    }
    
    public function __destruct() {
        fclose($this->handle);
        echo "文件已关闭\n";
    }
}

$fh = new FileHandler('test.txt');
// ... 使用文件
unset($fh);  // 触发析构函数
?>
Tip

析构函数常用于资源清理:关闭文件、断开数据库连接等。

19.4 $this 关键字

$this 指向当前对象实例:

<?php
class Person {
    public string $name;
    
    public function setName(string $name): void {
        $this->name = $name;  // $this->name 是属性,$name 是参数
    }
    
    public function introduce(): string {
        return "我是{$this->name}";
    }
}

$person = new Person();
$person->setName("李四");
echo $person->introduce();  // 我是李四
?>

19.5 类型声明在类中

<?php
class Product {
    public function __construct(
        public string $name,
        public float $price,
        public int $stock = 0
    ) {}
    
    public function isAvailable(): bool {
        return $this->stock > 0;
    }
    
    public function discount(float $rate): float {
        return $this->price * (1 - $rate);
    }
}

$product = new Product("手机", 2999.00, 10);
var_dump($product->isAvailable());  // true
echo $product->discount(0.1);       // 2699.1
?>

19.6 只读属性(PHP 8.1+)

<?php
class Order {
    public function __construct(
        public readonly int $id,
        public readonly string $customer,
        public float $total
    ) {}
}

$order = new Order(1, "张三", 199.00);
echo $order->id;        // 1
// $order->id = 2;      // 错误!readonly 属性不能修改
$order->total = 299;    // 正常,total 不是 readonly
?>
Note

readonly 属性只能在初始化时赋值(通常在构造函数中),之后不可修改。适用于 ID、创建时间等不变数据。


来源:参考了 w3cschool「PHP 面向对象」、runoob「PHP 面向对象」以及 php.net 官方文档,综合改写后所得。