مقالات علاء عامر

نقدم مجموعة شاملة من مقالات التعليمية الهامة في تطوير الويب لتحويل أفكارك إلى واقع رقمي

PHP 8.x: الميزات الحديثة والتحسينات الجديدة

PHP 2025-12-31 علاء عامر

PHP 8.x: الميزات الحديثة والتحسينات الجديدة

دليل متخصص من علاء عامر - مطور ومصمم مواقع وتطبيقات احترافية

PHP 8.x جلب تحسينات ثورية في الأداء والمميزات الجديدة. في هذا المقال، سنستكشف أهم الإضافات وكيفية استخدامها في المشاريع العملية.

2️⃣ Union Types - مرونة في تحديد الأنواع

الاستخدام الأساسي:

<?php
// PHP 8.0+

class UserService
{
    // يمكن أن تكون المعاملة string أو int
    public function findUser(string|int $identifier): User|null
    {
        if (is_string($identifier)) {
            return $this->findByEmail($identifier);
        }

        if (is_int($identifier)) {
            return $this->findById($identifier);
        }

        return null;
    }

    // Union Types مع أنواع مختلفة
    public function processPayment(array|PaymentData $paymentInfo): bool|string
    {
        if (is_array($paymentInfo)) {
            $paymentInfo = new PaymentData($paymentInfo);
        }

        $result = $this->gateway->process($paymentInfo);

        // إرجاع true للنجاح أو string للخطأ
        return $result->success ? true : $result->errorMessage;
    }

    // مع nullable
    public function getUserPreference(string $key): string|int|bool|null
    {
        return $_SESSION['user_preferences'][$key] ?? null;
    }
}

// استخدام Union Types في خصائص الكلاس
class ApiResponse
{
    public function __construct(
        public string|array $data,
        public int|string $statusCode = 200,
        public array|null $headers = null
    ) {}
}

// مع الـ Collections
class DataCollection
{
    private array $items = [];

    public function add(string|int|float|User $item): void
    {
        $this->items[] = $item;
    }

    public function get(int $index): string|int|float|User|null
    {
        return $this->items[$index] ?? null;
    }
}

4️⃣ Match Expression - بديل محسن لـ Switch

<?php
// Match Expression - أكثر دقة وأمان

class PaymentProcessor
{
    public function getPaymentGateway(string $type): PaymentGatewayInterface
    {
        // Match expression - PHP 8.0+
        return match ($type) {
            'credit_card', 'debit_card' => new CreditCardGateway(),
            'paypal' => new PayPalGateway(),
            'stripe' => new StripeGateway(),
            'bank_transfer' => new BankTransferGateway(),
            default => throw new InvalidArgumentException("Unsupported payment type: $type")
        };
    }

    public function calculateFee(string $type, float $amount): float
    {
        $feePercentage = match ($type) {
            'credit_card' => 2.9,
            'paypal' => 3.4,
            'stripe' => 2.9,
            'bank_transfer' => 0.5,
            'cash' => 0.0,
            default => 5.0 // رسوم عامة
        };

        return $amount * ($feePercentage / 100);
    }

    // Match مع expressions معقدة
    public function getShippingCost(int $weight, string $destination): float
    {
        return match (true) {
            $weight <= 1 && $destination === 'local' => 10.0,
            $weight <= 1 && $destination === 'national' => 25.0,
            $weight <= 5 && $destination === 'local' => 20.0,
            $weight <= 5 && $destination === 'national' => 40.0,
            $weight > 5 && $destination === 'local' => 30.0,
            $weight > 5 && $destination === 'national' => 60.0,
            default => 100.0 // شحن دولي
        };
    }
}

// Match مع Enums (PHP 8.1+)
enum Status: string
{
    case PENDING = 'pending';
    case PROCESSING = 'processing';
    case COMPLETED = 'completed';
    case FAILED = 'failed';
    case CANCELLED = 'cancelled';
}

class OrderService
{
    public function getStatusMessage(Status $status): string
    {
        return match ($status) {
            Status::PENDING => 'طلبك في انتظار المراجعة',
            Status::PROCESSING => 'جاري تجهيز طلبك',
            Status::COMPLETED => 'تم إكمال طلبك بنجاح',
            Status::FAILED => 'فشل في معالجة الطلب',
            Status::CANCELLED => 'تم إلغاء الطلب'
        };
    }

    public function canModify(Status $status): bool
    {
        return match ($status) {
            Status::PENDING, Status::PROCESSING => true,
            Status::COMPLETED, Status::FAILED, Status::CANCELLED => false
        };
    }
}

6️⃣ Constructor Property Promotion

<?php
// قبل PHP 8.0 - كود مطول
class UserOld
{
    private string $name;
    private string $email;
    private int $age;
    private bool $isActive;

    public function __construct(string $name, string $email, int $age, bool $isActive = true)
    {
        $this->name = $name;
        $this->email = $email;
        $this->age = $age;
        $this->isActive = $isActive;
    }

    public function getName(): string { return $this->name; }
    public function getEmail(): string { return $this->email; }
    // ... المزيد من getters
}

// PHP 8.0+ - كود مختصر وواضح
class User
{
    public function __construct(
        private string $name,
        private string $email,
        private int $age,
        private bool $isActive = true,
        public ?string $avatar = null  // يمكن دمج مستويات الوصول المختلفة
    ) {}

    // الـ getters اختيارية الآن
    public function getName(): string { return $this->name; }
    public function getEmail(): string { return $this->email; }

    // يمكن الوصول مباشرة للخصائص العامة
    public function hasAvatar(): bool
    {
        return $this->avatar !== null;
    }
}

// مع التحقق من صحة البيانات
class Product
{
    public function __construct(
        private string $name,
        private float $price,
        private int $stock,
        private bool $isActive = true
    ) {
        if ($this->price < 0) {
            throw new InvalidArgumentException('السعر لا يمكن أن يكون سالباً');
        }

        if ($this->stock < 0) {
            throw new InvalidArgumentException('المخزون لا يمكن أن يكون سالباً');
        }

        if (empty(trim($this->name))) {
            throw new InvalidArgumentException('اسم المنتج مطلوب');
        }
    }

    public function getPrice(): float { return $this->price; }
    public function getStock(): int { return $this->stock; }
    public function isAvailable(): bool { return $this->isActive && $this->stock > 0; }
}

8️⃣ JIT Compiler - تحسين الأداء

إعداد JIT في php.ini:

; تفعيل JIT
opcache.enable=1
opcache.jit_buffer_size=256M
opcache.jit=tracing

; إعدادات JIT متقدمة
opcache.jit_hot_loop=64
opcache.jit_hot_func=128
opcache.jit_hot_return=8
opcache.jit_hot_side_exit=8

; تفعيل JIT debugging (للتطوير فقط)
opcache.jit_debug=0

قياس تحسين الأداء:

<?php
// مثال على كود يستفيد من JIT

function fibonacci(int $n): int
{
    if ($n <= 1) return $n;
    return fibonacci($n - 1) + fibonacci($n - 2);
}

function benchmarkJIT()
{
    $start = microtime(true);

    // عمليات حسابية معقدة
    for ($i = 0; $i < 1000000; $i++) {
        $result = $i * $i + sqrt($i);
    }

    $end = microtime(true);

    return [
        'duration' => $end - $start,
        'memory' => memory_get_peak_usage(),
        'jit_enabled' => function_exists('opcache_get_status')
            ? (opcache_get_status()['jit']['enabled'] ?? false)
            : false
    ];
}

// Matrix operations التي تستفيد من JIT
class MatrixCalculator
{
    public static function multiply(array $a, array $b): array
    {
        $rows_a = count($a);
        $cols_a = count($a[0]);
        $cols_b = count($b[0]);

        $result = [];

        for ($i = 0; $i < $rows_a; $i++) {
            for ($j = 0; $j < $cols_b; $j++) {
                $result[$i][$j] = 0;
                for ($k = 0; $k < $cols_a; $k++) {
                    $result[$i][$j] += $a[$i][$k] * $b[$k][$j];
                }
            }
        }

        return $result;
    }
}

🔟 readonly Properties (PHP 8.1+)

<?php
// خصائص للقراءة فقط

class ImmutableUser
{
    public function __construct(
        public readonly string $id,
        public readonly string $name,
        public readonly string $email,
        public readonly DateTime $createdAt
    ) {}

    // لا يمكن تعديل الخصائص بعد الإنشاء
    // $user->name = 'new name'; // خطأ!
}

class Configuration
{
    public readonly string $appName;
    public readonly string $version;
    public readonly array $database;

    public function __construct(array $config)
    {
        $this->appName = $config['app_name'];
        $this->version = $config['version'];
        $this->database = $config['database'];

        // يمكن تعيين القيم فقط في الـ constructor
    }
}

// Value Objects مع readonly
class Money
{
    public function __construct(
        public readonly float $amount,
        public readonly string $currency
    ) {
        if ($amount < 0) {
            throw new InvalidArgumentException('المبلغ لا يمكن أن يكون سالباً');
        }
    }

    public function add(Money $other): Money
    {
        if ($this->currency !== $other->currency) {
            throw new InvalidArgumentException('العملات يجب أن تكون متطابقة');
        }

        return new Money($this->amount + $other->amount, $this->currency);
    }

    public function format(): string
    {
        return number_format($this->amount, 2) . ' ' . $this->currency;
    }
}

💡 نصائح الترقية إلى PHP 8.x

  1. اختبر شامل قبل الترقية في بيئة التطوير
  2. حدث المكتبات للتأكد من التوافق
  3. استخدم أدوات التحليل مثل PHPStan للكشف عن المشاكل
  4. فعل JIT تدريجياً ومراقبة الأداء
  5. ادرس الـ Breaking Changes في كل إصدار

الخطوة التالية

استكشف PHP 8.3 والميزات التجريبية القادمة، وتعلم Async PHP مع ReactPHP.

📩 تحتاج مساعدة في ترقية مشروعك لـ PHP 8.x؟

PHP PHP 8 Modern PHP JIT Union Types Attributes Performance
قسم المقالة
PHP

PHP 8.x: الميزات الحديثة والتحسينات الجديدة

استكشف أحدث ميزات PHP 8.x من Union Types إلى JIT Compiler وكيفية الاستفادة منها في مشاريعك.

PHP 8.x: الميزات الحديثة والتحسينات الجديدة
01

التواصل والاستشارة

تواصل مباشر عبر الواتساب أو الهاتف لفهم احتياجات مشروعك بدقة.

02

التخطيط والجدولة

وضع خطة عمل واضحة مع جدول زمني محدد لكل مرحلة من المشروع.

03

البرمجة والتطوير

تطوير المشروع بأحدث التقنيات لضمان الأداء والأمان العاليين.

04

المراجعة والتسليم

ختبار شامل ومراجعة دقيقة قبل التسليم النهائي للمشروع.

علاء عامر
علاء عامر

مطور ويب محترف بخبرة تزيد عن 10 سنوات في بناء حلول رقمية مبتكرة.

هل تحتاج هذه الخدمة؟

تواصل معي الآن للحصول على استشارة مجانية وعرض سعر

تواصل عبر واتساب رضاكم هو هدفنا الأسمى

عروض إضافية

  • صيانة وتحديث المواقع

    نحافظ على موقعك آمنًا ومحدّثًا دائمًا

  • ربط الأنظمة وواجهات البرمجة

    نربط أنظمتك بواجهات برمجية قوية ومرنة

  • تصميم وتحسين قواعد البيانات

    استعلامات أسرع وهيكلة أوضح وأخطاء أقل

  • تأمين المواقع والحماية المتقدمة

    حماية موقعك من التهديدات السيبرانية

  • أتمتة العمليات والمهام البرمجية

    نؤتمت المهام المتكررة ونوفّر وقتك دائمًا

لديك استفسار؟

اتصل بنا الآن

00201014714795

راسلنا عبر البريد الإلكتروني

[email protected]