class User {
private $name;
private $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
public function getName() {
return $this->name;
}
public function getEmail() {
return $this->email;
}
}
interface Shape {
public function area();
}
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;
}
}
class Bird {
public function fly() {
echo "I can fly.";
}
}
class Penguin extends Bird {
public function swim() {
echo "I can swim.";
}
}
$penguin = new Penguin();
$penguin->fly(); // I can fly.
$penguin->swim(); // I can swim.
interface Flyable {
public function fly();
}
interface Swimmable {
public function swim();
}
class Bird implements Flyable, Swimmable {
public function fly() {
echo "I can fly.";
}
public function swim() {
echo "I can swim.";
}
}
abstract class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Dog extends Animal {
public function bark() {
echo "Woof!";
}
}
class Math {
public function add($a, $b) {
return $a + $b;
}
public function subtract($a, $b) {
return $a - $b;
}
public function multiply($a, $b) {
return $a * $b;
}
public function divide($a, $b) {
if ($b == 0) {
throw new Exception("Division by zero");
}
return $a / $b;
}
}
$math = new Math();
echo $math->add(1, 2); // 3
echo $math->subtract(5, 3); // 2
echo $math->multiply(2, 3); // 6
echo $math->divide(6, 2); // 3
class User {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
}
class Order {
private $user;
private $items;
public function __construct(User $user, array $items) {
$this->user = $user;
$this->items = $items;
}
public function getUser() {
return $this->user;
}
public function getItems() {
return $this->items;
}
}
在一个典型的PHP应用中,通常会采用MVC(Model-View-Controller)的设计模式来组织代码。在这种模式下,Controller、Service、DAO(Data Access Object)、Logic和Model各自承担不同的责任:
Model:
DAO (Data Access Object):
Logic:
Service:
Controller:
Controller调用Service:
Service协调Model和DAO:
DAO与数据库交互:
Logic处理业务逻辑:
Model处理数据:
结果返回给Controller:
总的来说,各层之间的交互是有层次关系的,Controller是接收用户请求的入口,Service是处理业务逻辑的核心,DAO负责数据库交互,Logic处理业务逻辑的具体细节,Model负责数据的处理。它们共同协作,使得应用程序可以有组织、高效地处理业务需求。