Znalostní bázeCentrum zkoušek
CSČeština
Vybrat jazyk13

CKTIS / PHP

__construct

new předá argumenty konstruktoru `__construct`, který inicializuje instanci a nedeklaruje návratový typ.

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

Syntaxe

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

new předá argumenty konstruktoru __construct, který inicializuje instanci a nedeklaruje návratový typ. Potomek s vlastním konstruktorem musí pro inicializaci rodičovské části konstruktor rodiče výslovně zavolat. Bez vlastního konstruktoru zdědí přístupný rodičovský konstruktor.

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

Příklady

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

Výsledek

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

Zdroje