0
0
PHPprogramming~10 mins

Constructor inheritance in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a constructor in the parent class.

PHP
<?php
class ParentClass {
    public function [1]() {
        echo "Parent constructor called\n";
    }
}
?>
Drag options to blanks, or click blank then click option'
AParentClass
Bconstruct
C__construct
Dinit
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name without underscores like 'construct'.
Using the class name as constructor (old PHP style).
2fill in blank
medium

Complete the code to call the parent constructor from the child class.

PHP
<?php
class ChildClass extends ParentClass {
    public function __construct() {
        [1]();
        echo "Child constructor called\n";
    }
}
?>
Drag options to blanks, or click blank then click option'
Aparent::ParentClass
Bthis->__construct
Cself::__construct
Dparent::__construct
Attempts:
3 left
💡 Hint
Common Mistakes
Calling self::__construct() which calls the current class constructor recursively.
Using this instead of parent.
3fill in blank
hard

Fix the error in the child constructor to properly inherit the parent constructor.

PHP
<?php
class ChildClass extends ParentClass {
    public function __construct() {
        [1];
        echo "Child constructor called\n";
    }
}
?>
Drag options to blanks, or click blank then click option'
Aparent::__construct()
Bparent.__construct()
Cparent->__construct()
Dparent::__construct
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting parentheses when calling the method.
Using arrow -> or dot . instead of double colon.
4fill in blank
hard

Fill both blanks to create a child constructor that calls the parent constructor and sets a property.

PHP
<?php
class ChildClass extends ParentClass {
    public $name;
    public function __construct($name) {
        [1]();
        $this->[2] = $name;
    }
}
?>
Drag options to blanks, or click blank then click option'
Aparent::__construct
Bname
Cparent::__construct()
Dname()
Attempts:
3 left
💡 Hint
Common Mistakes
Calling parent constructor without parentheses.
Using incorrect property name or syntax.
5fill in blank
hard

Fill all three blanks to complete the child constructor that calls the parent constructor with a parameter and sets a property.

PHP
<?php
class ParentClass {
    public function __construct($id) {
        echo "Parent constructor with ID: $id\n";
    }
}

class ChildClass extends ParentClass {
    public $name;
    public function __construct($id, $name) {
        [1]([2]);
        $this->[3] = $name;
    }
}
?>
Drag options to blanks, or click blank then click option'
Aparent::__construct
B$id
Cname
Dparent::__construct()
Attempts:
3 left
💡 Hint
Common Mistakes
Calling parent constructor without passing the parameter.
Using incorrect syntax for calling the parent constructor.