Skip to content
PHP Logo

What potential issues can arise when calling the parent constructor within a normal function in PHP?

When calling the parent constructor within a normal function in PHP, the issue that can arise is that the parent constructor may not be properly initialized. To solve this, it is recommended to call the parent constructor within the child class constructor directly.

php
class ParentClass {
    public function __construct() {
        echo "Parent constructor called\n";
    }
}

class ChildClass extends ParentClass {
    public function __construct() {
        parent::__construct(); // Calling parent constructor directly
        echo "Child constructor called\n";
    }
}

$child = new ChildClass();