Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / PHP

__construct

Wyrażenie new przekazuje argumenty do konstruktora `__construct`, który inicjalizuje obiekt i nie deklaruje typu zwrotu.

Wersja: PHP 8.4; repository runtime, production runtime not attested

Składnia

public function __construct(string $label) { /* initialize */ }

Wyrażenie new przekazuje argumenty do konstruktora __construct, który inicjalizuje obiekt i nie deklaruje typu zwrotu. Potomek z własnym konstruktorem sam wywołuje konstruktor rodzica, jeśli potrzebuje jego inicjalizacji. Bez własnego konstruktora dziedziczy dostępny konstruktor rodzica.

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"]

Przykłady

<?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]);

Wynik

["A","[B]","unset"]

Źródła