PHP
ReflectionClass
ReflectionClass ile bir sınıfın property, method ve sabitlerini öğrenirsin.
ReflectionClass ile sınıf keşfi
ReflectionClass bir sınıfın haritasını çıkarır. getMethods() methodları, getProperties() property'leri ve getConstructor() kurucu methodu verir; hepsi reflection nesnesi olarak döner.
Kurucu yoksa getConstructor() null döndürür; bu yüzden kontrol etmeden kullanma. getShortName() namespace'siz kısa adı, isAbstract() ve isFinal() sınıfın niteliğini söyler.
Bilgiler okuma amaçlıdır: sınıfı değiştirmezler, yalnızca tarif ederler.
getConstructor ve getProperties
getConstructor() kurucu methodu bir ReflectionMethod olarak döndürür. Sınıfın kurucusu yoksa null alırsın; bu durumda argümansız new $class ile örnekleme yapılır.
getProperties() tüm property'leri ReflectionProperty dizisi olarak verir. Filtreli sürümü getProperties(ReflectionProperty::IS_PRIVATE) yalnız private olanları listeler.
Bu üç method birlikte bir sınıfın iskeletini dışarıdan ortaya çıkarır.
Uygulama UserService method adlarını yazdır
Aşağıdaki UserService sınıfı verilmiş. Bir ReflectionClass nesnesi oluştur ve getMethods() ile her methodun adını ayrı satıra yazdır.
Örnek çözümü göster
$rc = new ReflectionClass("UserService"); oluştur. foreach ($rc->getMethods() as $method) { echo $method->getName() . "\n"; } ile yazdır.
Örnek çözüm:
<?php
class UserService {
public function list(): array { return []; }
public function find(int $id): ?array { return null; }
}
$rc = new ReflectionClass("UserService");
foreach ($rc->getMethods() as $method) {
echo $method->getName() . "\n";
}
Kendini test et
-
getMethods() ile döngü kur
<?php
$rc = new ReflectionClass("UserService");
foreach ($rc->____() as $method) {
echo $method->getName() . "\n";
}
Cevabı göster
<?php
$rc = new ReflectionClass("UserService");
foreach ($rc->getMethods() as $method) {
echo $method->getName() . "\n";
}
-
getConstructor() ne döndürür?
- Kurucu methodu ReflectionMethod olarak, yoksa null
- Sınıfın tüm property'lerini dizi olarak
- Sınıfın tüm methodlarını dizi olarak
- Sınıfın tam adını dize olarak
Cevabı göster
Kurucu methodu ReflectionMethod olarak, yoksa null — Doğru. Kurucu bir ReflectionMethod'tur; yoksa null alırsın.
-
ReflectionClass methodlarını eşleştir
- getMethods
- Method listesini döndürür
- getProperties
- Property listesini döndürür
- getConstructor
- Kurucu methodu döndürür
- getShortName
- Kısa sınıf adını döndürür
Sıradaki ders: ReflectionMethod