0
0
PHPprogramming~5 mins

Constructor method in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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>&lt;?php
class Car {
  public $color;
  public function __construct($color) {
    $this->color = $color;
  }
}
$myCar = new Car('red');
echo $myCar->color; // Outputs: red
?&gt;</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+?
A__construct()
Bconstructor()
Cinit()
Dstart()
When is a constructor method called?
AWhen a method is called
BWhen an object is created
CWhen a property is accessed
DWhen the script ends
What keyword is used inside a constructor to refer to the current object?
A$this
B$self
C$current
D$obj
What happens if you create an object from a class without a constructor?
AThe object cannot be created
BPHP throws an error
CThe object is created without automatic setup
DThe object runs a default constructor
Which of these is a good reason to use a constructor?
ATo call static methods
BTo delay object creation
CTo delete the object
DTo set initial property values automatically
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.