CKTIS / PHP
__construct
new transmet les arguments à `__construct`, qui initialise l’instance sans déclarer de type de retour.
Version : PHP 8.4; repository runtime, production runtime not attested
Syntaxe
public function __construct(string $label) { /* initialize */ }new transmet les arguments à __construct, qui initialise l’instance sans déclarer de type de retour. Si la classe enfant définit un constructeur, elle doit appeler explicitement celui du parent pour exécuter son initialisation. Sans constructeur propre, elle hérite du constructeur accessible du parent.
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"]
Exemples
<?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]);
Résultat
["A","[B]","unset"]