Complete the code to define a constructor method in the class.
<?php class Car { public function [1]() { echo "Car created!"; } } $car = new Car(); ?>
In PHP, the constructor method is named __construct. It runs automatically when an object is created.
Complete the constructor to accept a parameter and assign it to a property.
<?php class Car { public $color; public function __construct([1]) { $this->color = $color; } } $car = new Car('red'); echo $car->color;
The constructor parameter must be a variable with a dollar sign, like $color, to receive the value.
Fix the error in the constructor method name.
<?php class Bike { public function [1]() { echo "Bike ready!"; } } $bike = new Bike(); ?>
The correct constructor method name in PHP is __construct with two underscores at the start.
Fill both blanks to create a constructor that sets two properties.
<?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.';
The constructor parameters must be variables with dollar signs: $name and $age.
Fill all three blanks to create a constructor that sets a property and calls a method.
<?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');
The constructor parameter is $breed. The method called is display, so both blanks use 'display'.