Challenge - 5 Problems
PHP Constructor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this PHP constructor example?
Consider the following PHP class with a constructor. What will be printed when the code runs?
PHP
<?php class Car { public $model; public function __construct($model) { $this->model = $model; echo "Car model is: " . $this->model . "\n"; } } $car = new Car("Toyota"); ?>
Attempts:
2 left
💡 Hint
Look at what the constructor does when the object is created.
✗ Incorrect
The constructor __construct is called automatically when a new object is created. It prints the model name passed during object creation.
❓ Predict Output
intermediate2:00remaining
What will be the value of $obj->name after this code runs?
Look at this PHP class with a constructor. What is the value of the property
name after creating the object?PHP
<?php class Person { public $name; public function __construct($name) { $this->name = $name; } } $obj = new Person("Alice"); // What is $obj->name? ?>
Attempts:
2 left
💡 Hint
The constructor sets the property from the argument.
✗ Incorrect
The constructor assigns the passed argument "Alice" to the property
name. So $obj->name is "Alice".🔧 Debug
advanced2:00remaining
What error does this PHP constructor code produce?
This PHP class tries to use a constructor but has a mistake. What error will it cause?
PHP
<?php class Animal { public $type; public function Animal($type) { $this->type = $type; } } $dog = new Animal("Dog"); echo $dog->type; ?>
Attempts:
2 left
💡 Hint
PHP 7+ uses __construct() as the constructor method, not the class name.
✗ Incorrect
In modern PHP versions, the constructor must be named __construct(). Naming it the same as the class does not work and __construct() is missing, causing a fatal error.
🧠 Conceptual
advanced2:00remaining
Which statement about PHP constructors is true?
Choose the correct statement about constructor methods in PHP classes.
Attempts:
2 left
💡 Hint
Think about what happens when you create a new object.
✗ Incorrect
In PHP, the __construct() method is called automatically when a new object is created. It can accept parameters and is the standard constructor method.
📝 Syntax
expert2:00remaining
Which option correctly defines a PHP constructor with a default parameter?
Select the PHP constructor method that correctly sets a default value for a parameter.
Attempts:
2 left
💡 Hint
Default parameters use = with quotes for strings.
✗ Incorrect
Option C correctly uses = "Guest" to set a default string parameter. Option C and C have invalid syntax. Option C misses quotes around Guest.