CKTIS / PHP
__construct
new geeft de argumenten door aan `__construct`, dat de instantie initialiseert zonder een retourtype te declareren.
Versie: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __construct(string $label) { /* initialize */ }new geeft de argumenten door aan __construct, dat de instantie initialiseert zonder een retourtype te declareren. Een kindklasse met een eigen constructor roept de ouderconstructor expliciet aan als diens initialisatie nodig is. Zonder eigen constructor erft zij de toegankelijke ouderconstructor.
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"]
Voorbeelden
<?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]);
Resultaat
["A","[B]","unset"]