0
0
PHPprogramming~10 mins

Constructor method 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 method in the class.

PHP
<?php
class Car {
    public function [1]() {
        echo "Car created!";
    }
}
$car = new Car();
?>
Drag options to blanks, or click blank then click option'
Acreate
Bconstructor
C__construct
Dinit
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'constructor' instead of '__construct'.
Forgetting the double underscores.
2fill in blank
medium

Complete the constructor to accept a parameter and assign it to a property.

PHP
<?php
class Car {
    public $color;
    public function __construct([1]) {
        $this->color = $color;
    }
}
$car = new Car('red');
echo $car->color;
Drag options to blanks, or click blank then click option'
A$color
Bcolor
C$this->color
Dthis->color
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the dollar sign in the parameter.
Using property syntax in the parameter list.
3fill in blank
hard

Fix the error in the constructor method name.

PHP
<?php
class Bike {
    public function [1]() {
        echo "Bike ready!";
    }
}
$bike = new Bike();
?>
Drag options to blanks, or click blank then click option'
Aconstruct
B__construct
C_construct
Dconstructor
Attempts:
3 left
💡 Hint
Common Mistakes
Using only one underscore.
Using 'constructor' instead of '__construct'.
4fill in blank
hard

Fill both blanks to create a constructor that sets two properties.

PHP
<?php
class Person {
    public $name;
    public $age;
    public function __construct([1], [2]) {
        $this->name = $name;
        $this->age = $age;
    }
}
$person = new Person('Alice', 30);
echo $person->name . ' is ' . $person->age . ' years old.';
Drag options to blanks, or click blank then click option'
A$name
B$age
Cname
Dage
Attempts:
3 left
💡 Hint
Common Mistakes
Using property names without dollar signs as parameters.
Mixing variable and property names.
5fill in blank
hard

Fill all three blanks to create a constructor that sets a property and calls a method.

PHP
<?php
class Dog {
    public $breed;
    public function __construct([1]) {
        $this->breed = $breed;
        $this->[2]();
    }
    private function [3]() {
        echo "Dog breed is set.";
    }
}
$dog = new Dog('Beagle');
Drag options to blanks, or click blank then click option'
A$breed
Bbark
CshowMessage
Ddisplay
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a method that is not defined.
Using method names that don't match.