CKTIS / PHP
__construct
new passa gli argomenti a `__construct`, che inizializza l’istanza senza dichiarare un tipo di ritorno.
Versione: PHP 8.4; repository runtime, production runtime not attested
Sintassi
public function __construct(string $label) { /* initialize */ }new passa gli argomenti a __construct, che inizializza l’istanza senza dichiarare un tipo di ritorno. Una sottoclasse con un proprio costruttore deve richiamare quello del padre per eseguirne l’inizializzazione. Altrimenti, in assenza di un proprio costruttore, eredita quello accessibile del padre.
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"]
Esempi
<?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]);
Risultato
["A","[B]","unset"]