CKTIS / PHP
__construct
new posreduje argumente konstruktorju `__construct`, ki inicializira primerek brez deklariranega tipa vrnjene vrednosti.
Različica: PHP 8.4; repository runtime, production runtime not attested
Sintaksa
public function __construct(string $label) { /* initialize */ }new posreduje argumente konstruktorju __construct, ki inicializira primerek brez deklariranega tipa vrnjene vrednosti. Če podrazred določi svoj konstruktor, mora za inicializacijo nadrazreda izrecno poklicati njegovega. Brez lastnega podeduje dostopni konstruktor nadrazreda.
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"]
Primeri
<?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]);
Rezultat
["A","[B]","unset"]