Baza znanjaCentar za ispite
HRHrvatski
Odaberi jezik13

CKTIS / PHP

__construct

new prosljeđuje argumente konstruktoru `__construct`, koji inicijalizira instancu bez deklariranog povratnog tipa.

Verzija: PHP 8.4; repository runtime, production runtime not attested

Sintaksa

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

new prosljeđuje argumente konstruktoru __construct, koji inicijalizira instancu bez deklariranog povratnog tipa. Potklasa s vlastitim konstruktorom mora izričito pozvati roditeljski ako treba njegovu inicijalizaciju. Bez vlastitog nasljeđuje dostupan roditeljski konstruktor.

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

Primjeri

<?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]);

Rezultat

["A","[B]","unset"]

Izvori