Recall & Review
beginner
What is a constructor method in PHP?
A constructor method is a special function inside a class that runs automatically when a new object is created. It usually sets up initial values or states for the object.Click to reveal answer
beginner
How do you name a constructor method in PHP 7 and later?
You name the constructor method
__construct(). This is a magic method that PHP calls automatically when creating an object.Click to reveal answer
beginner
What happens if you do not define a constructor in a PHP class?
If no constructor is defined, PHP creates the object without running any setup code automatically. You can still set properties later, but no automatic initialization happens.
Click to reveal answer
beginner
Show a simple example of a PHP class with a constructor that sets a property.Example:<br><pre><?php
class Car {
public $color;
public function __construct($color) {
$this->color = $color;
}
}
$myCar = new Car('red');
echo $myCar->color; // Outputs: red
?></pre>Click to reveal answer
beginner
Why use a constructor method instead of setting properties after creating an object?
Using a constructor ensures the object is ready to use immediately after creation. It helps avoid forgetting to set important properties and keeps code cleaner and safer.
Click to reveal answer
What is the correct name for a constructor method in PHP 7+?
✗ Incorrect
The magic method
__construct() is the standard constructor name in PHP 7 and later.When is a constructor method called?
✗ Incorrect
The constructor runs automatically right after an object is created.
What keyword is used inside a constructor to refer to the current object?
✗ Incorrect
In PHP,
$this refers to the current object inside class methods.What happens if you create an object from a class without a constructor?
✗ Incorrect
Without a constructor, the object is created but no automatic initialization code runs.
Which of these is a good reason to use a constructor?
✗ Incorrect
Constructors help set up initial values so the object is ready to use immediately.
Explain what a constructor method is and why it is useful in PHP classes.
Think about what happens right after you create a new object.
You got /4 concepts.
Write a simple PHP class with a constructor that sets a property called 'name'.
Use __construct and $this->name = ...
You got /4 concepts.