Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / PHP

__construct

new passa os argumentos a `__construct`, que inicializa a instância sem declarar um tipo de retorno.

Versão: PHP 8.4; repository runtime, production runtime not attested

Sintaxe

public function __construct(string $label) { /* initialize */ }

new passa os argumentos a __construct, que inicializa a instância sem declarar um tipo de retorno. Uma subclasse com construtor próprio tem de chamar expressamente o do pai quando precisa dessa inicialização. Sem construtor próprio, herda o construtor acessível do pai.

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"]

Exemplos

<?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"]

Fontes