PHP面向对象编程(OOP)有一些被广泛认可的最佳实践和常见模式,以下是主要的实践示例:
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 sendEmail($subject, $message) {
// 发送邮件逻辑
}
}
// 使用
$user = new User('John Doe', 'john@example.com');
echo $user->getName();
abstract class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function makeSound();
}
class Dog extends Animal {
public function makeSound() {
return "Woof!";
}
}
class Cat extends Animal {
public function makeSound() {
return "Meow!";
}
}
// 多态示例
$animals = [
new Dog('Buddy'),
new Cat('Whiskers')
];
foreach ($animals as $animal) {
echo $animal->makeSound();
}
interface Logger {
public function log($message);
}
class FileLogger implements Logger {
public function log($message) {
file_put_contents('app.log', $message, FILE_APPEND);
}
}
class DatabaseLogger implements Logger {
public function log($message) {
// 数据库记录逻辑
}
}
// 使用
function process(Logger $logger) {
$logger->log('Processing started');
}
$logger = new FileLogger();
process($logger);
class BankAccount {
private $balance = 0;
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
}
}
public function withdraw($amount) {
if ($amount > 0 && $amount <= $this->balance) {
$this->balance -= $amount;
return true;
}
return false;
}
public function getBalance() {
return $this->balance;
}
}
class MathOperations {
public static $pi = 3.14159;
public static function add($a, $b) {
return $a + $b;
}
}
// 使用
echo MathOperations::$pi;
echo MathOperations::add(5, 3);
class Magic {
private $data = [];
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
return $this->data[$name] ?? null;
}
public function __call($name, $arguments) {
echo "Calling method '$name' with arguments: " . implode(', ', $arguments);
}
}
$magic = new Magic();
$magic->property = 'value'; // 调用__set
echo $magic->property; // 调用__get
$magic->undefinedMethod('arg1', 'arg2'); // 调用__call
interface DatabaseConnection {
public function query($sql);
}
class MySQLConnection implements DatabaseConnection {
public function query($sql) {
// MySQL查询逻辑
}
}
class UserRepository {
private $db;
public function __construct(DatabaseConnection $db) {
$this->db = $db;
}
public function getUsers() {
return $this->db->query("SELECT * FROM users");
}
}
// 使用
$db = new MySQLConnection();
$userRepo = new UserRepository($db);
$users = $userRepo->getUsers();
class Database {
private static $instance = null;
private $connection;
private function __construct() {
$this->connection = new PDO("mysql:host=localhost;dbname=test", "user", "pass");
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
// 使用
$db = Database::getInstance();
$conn = $db->getConnection();
interface PaymentMethod {
public function pay($amount);
}
class CreditCardPayment implements PaymentMethod {
public function pay($amount) {
echo "Paying $amount via Credit Card";
}
}
class PayPalPayment implements PaymentMethod {
public function pay($amount) {
echo "Paying $amount via PayPal";
}
}
class PaymentFactory {
public static function create($type) {
switch ($type) {
case 'credit':
return new CreditCardPayment();
case 'paypal':
return new PayPalPayment();
default:
throw new Exception("Unknown payment method");
}
}
}
// 使用
$payment = PaymentFactory::create('credit');
$payment->pay(100);
trait Loggable {
public function log($message) {
echo "Logging: $message";
}
}
class User {
use Loggable;
public function create() {
$this->log("User created");
}
}
$user = new User();
$user->create();
这些示例涵盖了PHP OOP中最常见的实践模式,包括类设计、继承、接口、封装、设计模式等。遵循这些实践可以帮助编写更清晰、更可维护的面向对象PHP代码。
没有搜到相关的文章