面向对象编程 (oop) 的 php 实战案例:类:一个模板,用于创建包含数据和行为的对象。对象:由类创建的实例,可通过对象上的属性和方法进行访问。购物车案例:使用 oop 创建一个购物车系统,包括添加、移除和获取项目的功能。
PHP 面向对象编程:案例剖析
面向对象编程(OOP)是一种编程范例,它采用“对象”的概念将数据和行为绑定在一起。它使程序更易于管理、维护和扩展。
类的创建和使用
PHP 中的类是一个模板,用于创建对象。要创建一个类,请使用 class 关键字:
class Car {
public $make;
public $model;
public $year;
public function __construct($make, $model, $year) {
$this->make = $make;
$this->model = $model;
$this->year = $year;
}
public function getMake() {
return $this->make;
}
public function getModel() {
return $this->model;
}
public function getYear() {
return $this->year;
}
}
对象的创建和使用
要创建类的对象,请使用 new 关键字:
$car = new Car("Tesla", "Model 3", 2023);
可以通过对象上的属性名称访问对象属性:
echo $car->make; // 输出: Tesla
echo $car->model; // 输出: Model 3
echo $car->year; // 输出: 2023
还可以调用オブジェクト上的方法:
echo $car->getMake(); // 输出: Tesla
echo $car->getModel(); // 输出: Model 3
echo $car->getYear(); // 输出: 2023
实战案例:购物车
使用 OOP 创建一个购物车系统:
class Cart {
private $items = [];
public function addItem($item) {
$this->items[] = $item;
}
public function removeItem($item) {
unset($this->items[array_search($item, $this->items)]);
}
public function getItems() {
return $this->items;
}
}
$cart = new Cart();
$cart->addItem("Apple");
$cart->addItem("Banana");
$cart->addItem("Orange");
print_r($cart->getItems()); // 输出: ["Apple", "Banana", "Orange"]