CKTIS / PHP
__construct
Creating an instance with new invokes its applicable `__construct` with the supplied arguments.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __construct(string $label) { /* initialize */ }Creating an instance with new invokes its applicable __construct with the supplied arguments. The constructor initializes the existing instance and declares no return type. A child that defines its own constructor must call parent::__construct explicitly if parent initialization is needed. A child without its own constructor inherits an accessible parent constructor.
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"]
Examples
<?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]);
Result
["A","[B]","unset"]