TGViewer
Пых Пых @phpyh · 7.82K subscribers
Post #311 5.2K
$reflectionPromotedProperty->hasDefaultValue()

final class A
{
public function __construct(
public string $a = 'default',
) {}
}
$property = new ReflectionProperty(A::class, 'a');
var_dump($property->hasDefaultValue()); // false

Довольно контринтуитивно, что этот код выведет false.

Однако если развернуть promoted свойство в обычное, станет понятно, почему:

final class A
{
public string $a;

public function __construct(
string $a = 'default',
) {
$this->a = $a;
}
}
$parameter = new ReflectionParameter([A::class, '__construct'], 'a');
var_dump($parameter->isDefaultValueAvailable()); // true

Дефолтное значение имеет не свойство, а параметр конструктора!
Как следствие, вот такой код

$class = new ReflectionClass(A::class);
$a = $class->newInstanceWithoutConstructor();
var_dump($a->a);

выбросит Typed property A::$a must not be accessed before initialization.

https://3v4l.org/kkf24
  • 👍 48
  • 🔥 14
  • 🤩 2
More from @phpyh
  1. Sep 30, 2026🍺 BeerPHP AI Moscow Кажется, «неделя PHP» потихоньку превращается в месяц PHP. 😅 Будет 2…
  2. Sep 28, 2026Запустили Пыхник и неделю PHP! Залетайте на первый открытый доклад от Дмитрия Dantes про к…
  3. Sep 15, 2026Сейчас один человек с AI может выполнять работу целого IT-отдела. Только хуёво
  4. Sep 12, 2026Спасибо за заявки! Всем напишу в понедельник. Осталось 1 место.
  5. Sep 11, 2026Хардкорный курс асинхронного PHP https://hardcourse.ru/php/async
  6. Sep 11, 2026Ещё полчасика надо — сайт готов, расписываю программу! 🙏
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →