Interfaces & Abstract in PHP
Interfaces & Abstract in PHP
قائمة المصطلحات والتعريفات:
المقدمة:
في البرمجة الكائنية في PHP، تلعب الواجهات والفئات المجردة لها دورا مهما في تصميم الهيكلية الكائنية للتطبيقات. تستخدم الواجهات والفئات المجردة لتحقيق التعدد في التنفيذ وضمان التزام الفئات بطرق محددة
تهدف هذه الوثيقة إلى شرح مفهومي الواجهات (Interfaces) والفئات المجردة (Abstract Classes) في لغة البرمجة PHP
ما هي الواجهات (Interfaces)؟
هي نوع خاص من الفئات التي تحتوي على تعريفات للطرق دون تنفيذها. الفئة التي تطبق واجهة معينة يجب أن توفر تنفيذا لجميع الطرق المعرفة في تلك الواجهة.
كيفية استخدام الواجهات في PHP
يتم تعريف الواجهة باستخدام الكلمة المحجوزة interface. الفئة التي تطبق الواجهة تستخدم الكلمة المحجوزة implements
<?php
interface Animal {
public function makeSound();
}
class Dog implements Animal {
public function makeSound() {
echo "Woof!";
}
}
class Cat implements Animal {
public function makeSound() {
echo "Meow!";
}
}
$dog = new Dog();
$dog->makeSound(); // Woof!
$cat = new Cat();
$cat->makeSound(); // Meow!
?>
ما هي الفئات المجردة (Abstract Classes)؟
الفئات المجردة هي فئات تحتوي على طرق مجردة (بدون تنفيذ) وطرق أخرى قد تكون معرفة بالكامل. لا يمكن إنشاء كائنات مباشرة من الفئات المجردة، بل يجب توريثها وتوفير تنفيذ للطرق المجردة في الفئات الفرعية.
كيفية استخدام الفئات المجردة في PHP
يتم تعريف الفئة المجردة باستخدام الكلمة المحجوزة abstract. الطريقة المجردة يتم تعريفها باستخدام الكلمة المحجوزة abstract ولا تحتوي على جسم.
<?php
abstract class Vehicle {
protected $color;
public function __construct($color) {
$this->color = $color;
}
abstract public function move();
public function getColor() {
return $this->color;
}
}
class Car extends Vehicle {
public function move() {
echo "The car is driving.";
}
}
class Bicycle extends Vehicle {
public function move() {
echo "The bicycle is pedaling.";
}
}
$car = new Car("red");
$car->move(); // The car is driving.
$bicycle = new Bicycle("blue");
$bicycle->move(); // The bicycle is pedaling.
?>
الفرق بين الواجهات والفئات المجردة
أمثلة
نظام إدارة الدفع
<?php
interface PaymentGateway {
public function processPayment($amount);
}
abstract class OnlinePayment implements PaymentGateway {
protected $gatewayName;
public function __construct($gatewayName) {
$this->gatewayName = $gatewayName;
}
public function getGatewayName() {
return $this->gatewayName;
}
}
class PayPal extends OnlinePayment {
public function processPayment($amount) {
echo "Processing $" . $amount . " payment through " . $this->gatewayName;
}
}
class Stripe extends OnlinePayment {
public function processPayment($amount) {
echo "Processing $" . $amount . " payment through " . $this->gatewayName;
}
}
$paypal = new PayPal("PayPal");
$paypal->processPayment(100); // Processing $100 payment through PayPal
$stripe = new Stripe("Stripe");
$stripe->processPayment(200); // Processing $200 payment through Stripe
?>
المراجع:
ليست هناك تعليقات: