CKTIS / PHP
__construct
new предава аргументите на `__construct`, който инициализира обекта без деклариран тип на върнатата стойност.
Версия: PHP 8.4; repository runtime, production runtime not attested
Синтаксис
public function __construct(string $label) { /* initialize */ }new предава аргументите на __construct, който инициализира обекта без деклариран тип на върнатата стойност. Подклас със собствен конструктор трябва изрично да извика родителския, ако разчита на неговата инициализация. Без собствен конструктор наследява достъпния родителски.
class Label {
public string $text = "unset";
public function __construct(string $text) { $this->text = $text; }
}
class Plain extends Label {}
class Wrapped extends Label {
public function __construct(string $text) { parent::__construct("[" . $text . "]"); }
}
class Silent extends Label { public function __construct() {} }
echo json_encode([(new Plain("A"))->text, (new Wrapped("B"))->text, (new Silent())->text]);
["A","[B]","unset"]
Примери
<?php
class Label {
public string $text = "unset";
public function __construct(string $text) { $this->text = $text; }
}
class Plain extends Label {}
class Wrapped extends Label {
public function __construct(string $text) { parent::__construct("[" . $text . "]"); }
}
class Silent extends Label { public function __construct() {} }
echo json_encode([(new Plain("A"))->text, (new Wrapped("B"))->text, (new Silent())->text]);
Резултат
["A","[B]","unset"]