Ulaşım
- Adres: 2342 Sk, İpekyol, İpek Ap 49A, 63250 Haliliye/Şanlıurfa
- Telefon:
0505 532 36 38 - eMail: admin@alestaweb.com
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.
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).
new Foo()->bar() doğrudan zincirlenebilirPHP 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).
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).
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();
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)
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;
}
}
}
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...
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
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).
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...
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.
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.
$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
$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
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).
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
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!!!", "!");
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.
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;
}
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).
function foo(string $x = null) artık ?string $x = null yazılmalı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).
# 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
# composer.json'da PHP versiyonu güncelle
{
"require": {
"php": "^8.4"
}
}
# Update
composer update --with-all-dependencies
// Ö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).
Alesta Web olarak tüm kod örneklerini PHP 8.4.3 sürümünde test ettik (tested on PHP 8.4.3).
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:
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.