CKTIS / PHP
__construct
new odovzdá argumenty konštruktoru `__construct`, ktorý inicializuje inštanciu a nedeklaruje návratový typ.
Verzia: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __construct(string $label) { /* initialize */ }new odovzdá argumenty konštruktoru __construct, ktorý inicializuje inštanciu a nedeklaruje návratový typ. Potomok s vlastným konštruktorom musí potrebnú inicializáciu rodiča výslovne zavolať. Bez vlastného konštruktora zdedí prístupný konštruktor rodiča.
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"]
Prí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ýsledok
["A","[B]","unset"]