首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[分享]掌握PHP面向对象编程:5个实用实例轻松入门

发布于 2025-07-16 12:36:32
0
678

实例1:简单的用户管理系统

1.1 类定义

class User { public $name; public $email; public $password; public function __construct($name, $email, $password) { $this->name = $name; $this->email = $email; $this->password = $password; } public function displayInfo() { echo "Name: " . $this->name . "<br>"; echo "Email: " . $this->email . "<br>"; }
}

1.2 实例化对象

$user = new User("John Doe", "john@example.com", "password123");
$user->displayInfo();

1.3 输出

Name: John Doe
Email: john@example.com

实例2:图书管理系统

2.1 类定义

class Book { public $title; public $author; public $isbn; public function __construct($title, $author, $isbn) { $this->title = $title; $this->author = $author; $this->isbn = $isbn; } public function displayInfo() { echo "Title: " . $this->title . "<br>"; echo "Author: " . $this->author . "<br>"; echo "ISBN: " . $this->isbn . "<br>"; }
}

2.2 实例化对象

$book = new Book("PHP Programming", "Jane Doe", "1234567890");
$book->displayInfo();

2.3 输出

Title: PHP Programming
Author: Jane Doe
ISBN: 1234567890

实例3:汽车租赁系统

3.1 类定义

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 displayInfo() { echo "Make: " . $this->make . "<br>"; echo "Model: " . $this->model . "<br>"; echo "Year: " . $this->year . "<br>"; }
}

3.2 实例化对象

$car = new Car("Toyota", "Corolla", 2020);
$car->displayInfo();

3.3 输出

Make: Toyota
Model: Corolla
Year: 2020

实例4:在线商店购物车

4.1 类定义

class Cart { public $items = []; public function addItem($item) { $this->items[] = $item; } public function displayItems() { foreach ($this->items as $item) { echo "Item: " . $item . "<br>"; } }
}

4.2 实例化对象

$cart = new Cart();
$cart->addItem("Book");
$cart->addItem("Pen");
$cart->displayItems();

4.3 输出

Item: Book
Item: Pen

实例5:博客系统

5.1 类定义

class BlogPost { public $title; public $content; public $date; public function __construct($title, $content, $date) { $this->title = $title; $this->content = $content; $this->date = $date; } public function displayPost() { echo "Title: " . $this->title . "<br>"; echo "Content: " . $this->content . "<br>"; echo "Date: " . $this->date . "<br>"; }
}

5.2 实例化对象

$post = new BlogPost("PHP OOP", "This is a post about PHP OOP.", "2025-05-19");
$post->displayPost();

5.3 输出

Title: PHP OOP
Content: This is a post about PHP OOP.
Date: 2025-05-19
评论
一个月内的热帖推荐
极兔cdn
Lv.1普通用户

3

帖子

6

小组

37

积分

赞助商广告
站长交流