0
0
PHPprogramming~20 mins

Constructor method in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PHP Constructor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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");
?>
ANo output
BCar model is:
CFatal error: Constructor method not found
DCar model is: Toyota
Attempts:
2 left
💡 Hint
Look at what the constructor does when the object is created.
Predict Output
intermediate
2: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?
?>
A"Alice"
B"name"
CUndefined property error
Dnull
Attempts:
2 left
💡 Hint
The constructor sets the property from the argument.
🔧 Debug
advanced
2: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;
?>
AOutputs: Dog
BNotice: Undefined property: Animal::$type
CFatal error: Call to undefined method Animal::__construct()
DParse error: syntax error
Attempts:
2 left
💡 Hint
PHP 7+ uses __construct() as the constructor method, not the class name.
🧠 Conceptual
advanced
2:00remaining
Which statement about PHP constructors is true?
Choose the correct statement about constructor methods in PHP classes.
AConstructors cannot accept parameters in PHP.
BThe constructor method __construct() is called automatically when an object is created.
CThe constructor method must always be named after the class name.
DYou must call the constructor manually after creating an object.
Attempts:
2 left
💡 Hint
Think about what happens when you create a new object.
📝 Syntax
expert
2: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.
Apublic function __construct($name ?: "Guest") { $this->name = $name; }
Bpublic function __construct($name) = "Guest" { $this->name = $name; }
Cpublic function __construct($name = "Guest") { $this->name = $name; }
Dpublic function __construct($name = Guest) { $this->name = $name; }
Attempts:
2 left
💡 Hint
Default parameters use = with quotes for strings.