CKTIS / PHP
__construct
new übergibt die Argumente an `__construct`.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __construct(string $label) { /* initialize */ }new übergibt die Argumente an __construct. Der Konstruktor initialisiert die Instanz und deklariert keinen Rückgabetyp. Eine Unterklasse mit eigenem Konstruktor muss die benötigte Initialisierung der Basisklasse ausdrücklich aufrufen, andernfalls erbt sie ohne eigenen Konstruktor den zugänglichen Elternkonstruktor.
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"]
Beispiele
<?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]);
Ergebnis
["A","[B]","unset"]