Are Parent constructors called implicitly inside a class constructor?
Are Parent constructors called implicitly inside a class constructor?
In PHP, parent constructors are not called implicitly inside a class constructor. If you want to call a parent constructor within a child class, you need to do so explicitly using the parent::__construct() syntax. Here’s an example to illustrate this:
<?php
class ParentClass {
public function __construct() {
echo "Parent constructor called\n";
}
}
class ChildClass extends ParentClass {
public function __construct() {
// Explicitly calling the parent constructor
parent::__construct();
echo "Child constructor called\n";
}
}
// Creating an instance of ChildClass
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.