面向对象编程(Object-Oriented Programming,简称 OOP)是一种编程范式,它通过“对象”来组织代码。对象是数据和操作这些数据的方法的封装体。这种编程方式可以更好地模拟现实世界中的事物,并且有助于提高代码的可维护性、扩展性和复用性。
类与对象
类的定义
类是创建对象的蓝图或模板。它定义了对象的属性(数据成员)和行为(成员方法)。下面是一个简单的类定义示例:
// www.javascriptcn.com code example
class Car {
public $brand;
public $model;
// 构造函数
function __construct($brand, $model) {
$this->brand = $brand;
$this->model = $model;
}
// 成员方法
function displayCarInfo() {
echo "Brand: " . $this->brand . ", Model: " . $this->model;
}
}对象的创建与使用
一旦定义了类,就可以根据这个类创建对象。对象是类的实例。可以通过 new 关键字创建对象,并调用其方法:
$car1 = new Car("Toyota", "Corolla");
$car1->displayCarInfo(); // 输出:Brand: Toyota, Model: Corolla继承
继承允许我们定义一个类来继承另一个类的属性和方法。被继承的类称为父类(基类),继承的类称为子类(派生类)。
基本继承概念
子类可以重写或扩展父类的行为。这使得子类能够保持父类的通用特性,同时具有自己的特殊行为。
// www.javascriptcn.com code example
// 父类
class Vehicle {
public $type;
function __construct($type) {
$this->type = $type;
}
function drive() {
return "Driving a " . $this->type;
}
}
// 子类
class Car extends Vehicle {
public $brand;
public $model;
function __construct($brand, $model, $type) {
parent::__construct($type); // 调用父类构造函数
$this->brand = $brand;
$this->model = $model;
}
function displayCarInfo() {
echo "Brand: " . $this->brand . ", Model: " . $this->model . ", Type: " . $this->type;
}
}
$car2 = new Car("Honda", "Civic", "Car");
echo $car2->drive(); // 输出:Driving a Car
$car2->displayCarInfo(); // 输出:Brand: Honda, Model: Civic, Type: Car封装
封装是指将数据(属性)和操作数据的方法绑定在一起,并限制外部直接访问内部数据。这样做的目的是为了保护数据不被随意修改,从而保证程序的稳定性和安全性。
私有属性和方法
在 PHP 中,可以使用 private 或 protected 关键字来声明私有或受保护的属性和方法。外部代码不能直接访问这些属性和方法,只能通过公共方法间接访问。
// www.javascriptcn.com code example
class BankAccount {
private $balance;
public function __construct($initialBalance) {
$this->balance = $initialBalance;
}
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
}
}
public function withdraw($amount) {
if ($amount > 0 && $amount <= $this->balance) {
$this->balance -= $amount;
}
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount(100);
$account->deposit(50);
$account->withdraw(30);
echo $account->getBalance(); // 输出:120多态
多态是指允许不同类的对象对同一消息做出响应的能力,即同一个接口可以被多个类实现。多态增加了程序的灵活性和可扩展性。
方法重载
虽然 PHP 不支持真正的多态(如 Java 中的方法重载),但可以通过接口或抽象类实现类似的功能。
// www.javascriptcn.com code example
interface Shape {
public function area();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return pi() * $this->radius * $this->radius;
}
}
class Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function area() {
return $this->width * $this->height;
}
}
function printArea(Shape $shape) {
echo "Area: " . $shape->area();
}
$circle = new Circle(5);
$rectangle = new Rectangle(4, 6);
printArea($circle); // 输出:Area: 78.53981633974483
printArea($rectangle); // 输出:Area: 24以上是 PHP 面向对象编程的基础内容,包括类与对象、继承、封装以及多态的概念。通过理解和应用这些概念,可以编写出更加健壮、易于维护的代码。