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
- Are there specific online resources or tutorials that can guide PHP users in migrating from file-based data manipulation to database management for improved efficiency and scalability?
- Are short open tags recommended for PHP development, and what are the potential pitfalls?
- What is the difference between using self and __CLASS__ in PHP when creating objects within a class?