CKTIS / PHP
__construct
new pasa los argumentos a `__construct`, que inicializa la instancia sin declarar tipo de retorno.
Versión: PHP 8.4; repository runtime, production runtime not attested
Sintaxis
public function __construct(string $label) { /* initialize */ }new pasa los argumentos a __construct, que inicializa la instancia sin declarar tipo de retorno. Una subclase con constructor propio debe llamar explícitamente al del padre si necesita su inicialización. Sin constructor propio hereda el constructor accesible 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"]
Ejemplos
<?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]);
Resultado
["A","[B]","unset"]