PHP 8.4 Yenilikleri: Property Hooks, Asymmetric Visibility ve Lazy Objects Rehberi (2026)

Ana SayfaHaberler › PHP 8.4 Yenilikleri: Property Hooks, Asymmetric Visi...

PHP 8.4 Yenilikleri: Property Hooks, Asymmetric Visibility ve Lazy Objects Rehberi (2026)

16.05.2026 1 görüntülenme

PHP 8.4 ile birlikte dilin nesne yönelimli (object-oriented) tarafında ciddi modernizasyon yaşandı. Alesta Web olarak bu yazımızda; Property Hooks (özellik kancaları), Asymmetric Visibility (asimetrik görünürlük), #[\Deprecated] attribute, lazy objects ve yeni array fonksiyonları gibi PHP 8.4'ün en önemli yeniliklerini (the most important new features of PHP 8.4) gerçek dünyaya yakın kod örnekleriyle anlatıyoruz. PHP geliştiriciyseniz (if you are a PHP developer), bu rehberi mutlaka okuyun.

1. PHP 8.4 Genel Bakış (PHP 8.4 Overview)

PHP 8.4, 21 Kasım 2024'te (November 21, 2024) yayınlandı ve PHP 8.x serisinin en büyük güncellemelerinden biri oldu. PHP topluluğunun yıllardır beklediği Property Hooks ve Asymmetric Visibility gibi büyük dil özellikleri (major language features), nihayet bu sürümle birlikte geldi. Alesta Web olarak PHP 8.4'ün getirdiklerini Türkiye PHP topluluğu için derledik (compiled for the Turkish PHP community).

Öne Çıkan Özellikler (Key Features)

  • Property Hooks: Get/set kancaları — Kotlin ve C# benzeri (similar to Kotlin and C#)
  • Asymmetric Visibility: Property için ayrı read/write görünürlüğü (separate read/write visibility)
  • #[\Deprecated] Attribute: Native deprecation annotations
  • array_find, array_find_key, array_any, array_all: Yeni dahili fonksiyonlar (new built-in functions)
  • Lazy Objects API: Lazy ghost ve lazy proxy objeler (lazy ghost and proxy objects)
  • mb_trim, mb_ltrim, mb_rtrim: Multibyte (UTF-8) trim fonksiyonları
  • HTML5 native parser: Dom\HTMLDocument sınıfı (Dom\HTMLDocument class)
  • Parantezsiz new expression chaining: new Foo()->bar() doğrudan zincirlenebilir
💡 Bilgi / Info:

PHP 8.4 active support 31 Aralık 2026'ya kadar (until December 31, 2026), security support ise 31 Aralık 2028'e kadar (until December 31, 2028) sürer. Yani bu sürüm uzun ömürlü (long-term).

2. Property Hooks: Get/Set Kancaları (The Big One!)

Property Hooks, PHP 8.4'ün en çok beklenen özelliğidir (the most anticipated feature). Kotlin'deki property accessors veya C#'taki property get/set'lere benzer şekilde, sınıf property'lerine doğrudan getter/setter mantığı ekleyebilirsiniz (you can add getter/setter logic directly to class properties).

2.1 Eski Yöntem (Pre-PHP 8.4) — Getter/Setter Metotları

class User {
    private string $firstName;
    private string $lastName;

    public function getFullName(): string {
        return $this->firstName . ' ' . $this->lastName;
    }

    public function setFullName(string $value): void {
        $parts = explode(' ', $value, 2);
        $this->firstName = $parts[0];
        $this->lastName  = $parts[1] ?? '';
    }
}

$u = new User();
$u->setFullName('Ahmet Yılmaz');
echo $u->getFullName();

2.2 Yeni Yöntem (PHP 8.4) — Property Hooks

class User {
    public string $firstName = '';
    public string $lastName  = '';

    public string $fullName {
        get => $this->firstName . ' ' . $this->lastName;
        set(string $value) {
            $parts = explode(' ', $value, 2);
            $this->firstName = $parts[0];
            $this->lastName  = $parts[1] ?? '';
        }
    }
}

$u = new User();
$u->fullName = 'Ahmet Yılmaz';  // setter çalışır (setter triggered)
echo $u->fullName;             // 'Ahmet Yılmaz' (getter çalışır)
✅ Avantajlar / Advantages:
  • Daha temiz API (cleaner API)
  • Daha az boilerplate kod
  • Doğrudan property erişimi (direct property access)
  • Geriye uyumlu — get/set metotlu eski kodu refactor etmek kolay

2.3 Validation (Doğrulama) ile Property Hook

class Product {
    private float $_price = 0;

    public float $price {
        get => $this->_price;
        set(float $value) {
            if ($value < 0) {
                throw new InvalidArgumentException('Fiyat negatif olamaz (price cannot be negative)');
            }
            $this->_price = $value;
        }
    }
}

2.4 Virtual Property (Sadece Get)

class Circle {
    public function __construct(public float $radius) {}

    // Hesaplanmış özellik (computed property) — sadece getter
    public float $area {
        get => M_PI * $this->radius ** 2;
    }
}

$c = new Circle(5);
echo $c->area; // 78.54...

3. Asymmetric Visibility (Asimetrik Görünürlük)

Asymmetric Visibility sayesinde bir property için read ve write görünürlüğünü ayrı ayrı belirleyebilirsiniz (you can set read and write visibility separately). Bu, immutable benzeri davranış (immutable-like behavior) sağlar.

class Book {
    public function __construct(
        public private(set) string $title,
        public protected(set) int $price
    ) {}
}

$book = new Book('PHP 8.4 Rehberi', 199);

echo $book->title;  // OK — public read
$book->title = 'X'; // ❌ Error — private(set) — sadece sınıf içinden yazılabilir

3.1 Pratik Kullanım: Domain Entity

class Order {
    public private(set) string $status = 'pending';
    public private(set) ?DateTimeImmutable $shippedAt = null;

    public function ship(): void {
        $this->status    = 'shipped';
        $this->shippedAt = new DateTimeImmutable();
    }
}

$order = new Order();
echo $order->status;     // 'pending' — OK read
$order->ship();           // OK — status sınıf içinden değişir
$order->status = 'cancelled'; // ❌ Error

Alesta Web ipucu (Alesta Web tip): DDD (Domain-Driven Design) projelerinde domain entity'lerinizdeki value object'leri korumak için private(set) idealdir (ideal for protecting value objects in DDD entities).

4. #[\Deprecated] Attribute — Native Deprecation Annotations

PHP 8.4 öncesinde deprecation için trigger_error(..., E_USER_DEPRECATED) kullanılırdı. Artık native bir attribute var (now there is a native attribute).

class Calculator {
    #[\Deprecated(
        message: 'Use add() method instead',
        since: '2.0'
    )]
    public function sum(int $a, int $b): int {
        return $a + $b;
    }

    public function add(int $a, int $b): int {
        return $a + $b;
    }
}

$calc = new Calculator();
$calc->sum(2, 3);  // PHP Deprecated: ...method is deprecated...
✅ Avantaj / Advantage:

IDE'ler (PHPStorm, VSCode + Intelephense) bu attribute'u algılayıp uyarı verir (IDEs detect and warn). Static analysis araçları (PHPStan, Psalm) da entegre eder.

5. Yeni Array Fonksiyonları (New Array Functions)

PHP 8.4 ile birlikte 4 yeni dahili array fonksiyonu geldi (4 new built-in array functions arrived). Bu fonksiyonlar JavaScript veya Python developer'ların aşina olduğu pattern'leri PHP'ye getiriyor.

5.1 array_find ve array_find_key

$users = [
    ['name' => 'Ahmet', 'age' => 28],
    ['name' => 'Mehmet', 'age' => 35],
    ['name' => 'Ayşe',  'age' => 24],
];

// İlk eşleşen elemanı bul (find first matching element)
$adult = array_find($users, fn($u) => $u['age'] >= 30);
// ['name' => 'Mehmet', 'age' => 35]

// Anahtarı al (get the key)
$key = array_find_key($users, fn($u) => $u['name'] === 'Ayşe');
// 2

5.2 array_any ve array_all

$ages = [28, 35, 24, 42];

// En az bir tane eşleşen var mı? (is there at least one match?)
$hasAdult = array_any($ages, fn($age) => $age >= 30);
// true

// Hepsi eşleşiyor mu? (do all match?)
$allAdults = array_all($ages, fn($age) => $age >= 18);
// true
💡 Alesta Web İpucu:

Eski PHP sürümlerinde array_filter + reset kombosu ile aynı işi yapıyorduk. Artık tek fonksiyon yeterli (now one function is enough) ve performans daha iyi (better performance).

6. Lazy Objects API (Tembel Nesneler)

PHP 8.4 ile ReflectionClass üzerinden lazy ghost ve lazy proxy nesneler oluşturabilirsiniz (you can create lazy ghost and lazy proxy objects). ORM'ler için (for ORMs) çok önemli bir özellik.

class User {
    public function __construct(
        public int $id,
        public string $name,
        public string $email
    ) {}
}

$reflector = new ReflectionClass(User::class);

// Lazy ghost: nesne ilk erişildiğinde initialize edilir
$lazyUser = $reflector->newLazyGhost(function(User $u) {
    // DB'den verileri çek (fetch from DB)
    $data = fetchUserFromDb(42);
    $u->__construct($data['id'], $data['name'], $data['email']);
});

// Buraya kadar DB sorgusu yok (no DB query yet)
echo $lazyUser->id;  // İlk erişim: closure çalışır, sonra 42
✅ Kullanım Alanları (Use Cases):
  • ORM lazy loading (Doctrine ORM, Eloquent benzeri)
  • Heavy domain object'lerin geç başlatılması (deferred initialization)
  • Dependency Injection container'larda lazy resolution

7. mb_trim, mb_ltrim, mb_rtrim (UTF-8 Trim Fonksiyonları)

Türkçe karakter işleyen geliştiriciler için (for developers working with Turkish characters) harika bir haber: trim(), ltrim(), rtrim()'nin multibyte versiyonları geldi.

// Eski yöntem (ASCII güvensiz, ASCII-unsafe)
$str = trim(" Türkçe metin "); // Japon boşluk karakteri trim edilmez

// PHP 8.4 (UTF-8 destekli)
$clean = mb_trim(" Türkçe metin ");      // 'Türkçe metin'
$left  = mb_ltrim("  Merhaba", " ");
$right = mb_rtrim("Selam!!!", "!");
⚠️ Dikkat / Warning:

Türkçe karakterlerle çalışan formları temizlerken artık mb_trim tercih edin (prefer mb_trim for Turkish form cleaning). UTF-8 zero-width space ve unicode whitespace karakterleri de trim edilir.

8. HTML5 Native Parser — Dom\HTMLDocument

PHP'nin DOM eklentisi 20+ yıldır libxml2 üzerinden HTML4 standardına göre çalışıyordu (worked according to HTML4 standard). PHP 8.4 ile birlikte WHATWG HTML5 standardına uyumlu Dom\HTMLDocument sınıfı geldi.

use Dom\HTMLDocument;

$html = '<article><h1>Başlık</h1><p>Türkçe içerik</p></article>';

// HTML5 parser ile yükle (load with HTML5 parser)
$doc = HTMLDocument::createFromString($html);

$articles = $doc->getElementsByTagName('article');
foreach ($articles as $article) {
    echo $article->textContent;
}
✅ Faydaları (Benefits):
  • UTF-8 native (no encoding hacks)
  • HTML5 self-closing tag desteği (HTML5 self-closing tag support)
  • Modern semantic elementler doğru parse edilir
  • Hata yönetimi modern (modern error handling)

9. New Expression Chaining (Parantezsiz Method Chain)

PHP 8.4 öncesinde (new Foo())->bar() şeklinde parantez gerekirdi. Artık doğrudan zincirlenebilir (now directly chainable).

// ESKİ (pre-8.4)
$result = (new HttpClient())->get('/api/users')->json();

// YENİ (PHP 8.4)
$result = new HttpClient()->get('/api/users')->json();

Daha kısa ve daha okunabilir (shorter and more readable). Alesta Web ekibi olarak factory pattern'lerde ciddi temizlik sağladığını gördük (significantly cleaner factory patterns).

10. Deprecated ve Breaking Changes (Dikkat!)

⚠️ Deprecated Özellikler:
  • Implicit nullable parameters: function foo(string $x = null) artık ?string $x = null yazılmalı
  • get_class() ve get_parent_class() parametresiz: Artık zorunlu argüman gerekiyor (now requires argument)
  • E_STRICT constant: Tamamen kaldırıldı (completely removed)
  • Soft deprecation: session.sid_length ve session.sid_bits_per_character
💡 Migration İpucu:

Statik analiz araçları (PHPStan level 8+, Psalm level 1) bu uyarıları yakalar. Migration öncesi mutlaka vendor/bin/phpstan analyse --level=8 çalıştırın (run before migration).

11. PHP 8.3'ten 8.4'e Migration Rehberi

11.1 Sunucuda Kurulum (Server Installation — Ubuntu/Debian)

# Ondrej PPA ekle (add PPA)
sudo add-apt-repository ppa:ondrej/php
sudo apt update

# PHP 8.4 ve yaygın eklentileri kur (install PHP 8.4)
sudo apt install php8.4 php8.4-fpm php8.4-mysql php8.4-mbstring \
    php8.4-curl php8.4-xml php8.4-zip php8.4-intl php8.4-gd

# Versiyon kontrol (check version)
php8.4 -v

11.2 Composer Bağımlılıklarını Güncelle (Update Composer)

# composer.json'da PHP versiyonu güncelle
{
    "require": {
        "php": "^8.4"
    }
}

# Update
composer update --with-all-dependencies

11.3 Implicit Nullable Düzeltmesi (Implicit Nullable Fix)

// ÖNCE (deprecated)
function processUser(string $name = null, int $age = null) { ... }

// SONRA (PHP 8.4 doğru)
function processUser(?string $name = null, ?int $age = null) { ... }

Alesta Web ipucu: rector aracı bu refactor'ı otomatik yapar (Rector tool does this refactor automatically).

11.4 Framework Uyumluluğu (Framework Compatibility)

  • Laravel 11+: PHP 8.4 tam destekli (full support)
  • Symfony 7.1+: PHP 8.4 tam destekli
  • WordPress 6.7+: PHP 8.4 stable destek
  • Drupal 11: PHP 8.4 destekli

12. 📚 Kaynaklar ve Referanslar / Sources and References

Alesta Web olarak tüm kod örneklerini PHP 8.4.3 sürümünde test ettik (tested on PHP 8.4.3).

✅ Sonuç: PHP 8.4'e Geçmeli mi? (Should You Upgrade?)

PHP 8.4, dilin nesne yönelimli tarafında yıllardır beklenen yenilikleri getiriyor (long-awaited OOP features). Property Hooks ve Asymmetric Visibility sayesinde modern PHP kodu çok daha temiz ve maintainable hale geliyor (much cleaner and more maintainable).

Hızlı Karar Rehberi / Quick Decision Guide:

  • Yeni proje: PHP 8.4 ile başlayın
  • Laravel 11+/Symfony 7.1+ kullanıcısı: Hemen migrate edebilirsiniz (migrate immediately)
  • ⚠️ Eski WordPress eklentileri: Eklenti uyumluluğunu kontrol edin (check plugin compatibility)
  • ⚠️ Implicit nullable kullanan kod: Rector ile refactor edin (refactor with Rector)

Faydalı Linkler / Useful Links:

Alesta Web ekibi olarak PHP 8.4 hakkında sorularınız varsa (if you have questions about PHP 8.4), yorum bölümünden bize ulaşabilirsiniz. Modern PHP rehberlerini takip etmek için alestaweb.com'u ziyaret edin.

© 2026 AlestaWeb - Tüm hakları saklıdır.

Etiketler: Haberler