How can you call a constructor with parameters from a subclass in PHP?
To call a constructor with parameters from a subclass in PHP, you can use the parent::__construct() method within the subclass constructor. This allows you to pass parameters to the parent class constructor when creating an instance of the subclass. By using this method, you can initialize the parent class properties with the provided parameters in the subclass constructor.
class ParentClass {
public function __construct($param1, $param2) {
// constructor logic here
}
}
class SubClass extends ParentClass {
public function __construct($param1, $param2, $param3) {
parent::__construct($param1, $param2);
// additional subclass constructor logic here
}
}
// Creating an instance of SubClass with parameters for both parent and subclass constructor
$subInstance = new SubClass('param1_value', 'param2_value', 'param3_value');
Keywords
Related Questions
- How can a WebSocket server be started and managed from the console in PHP applications, and what are the best practices for ensuring continuous operation?
- What are the best practices for displaying images in a gallery with thumbnails that expand when clicked on?
- How does the syntax for calling a public method as static work in PHP?