What is the purpose of a constructor in PHP?
B
To initialize object properties when an object is created
D
To delete class variables
Analysis & Theory
A constructor is a special function that is automatically called when an object is created to initialize properties.
What is the correct name of the constructor method in PHP?
Analysis & Theory
`__construct()` is the magic method used as a constructor in PHP classes.
When is the constructor function called?
B
When the class is defined
C
When an object is created from the class
D
When the object is deleted
Analysis & Theory
The constructor is called automatically when an object is instantiated from a class.
What happens if a class does not have a constructor defined?
B
PHP uses a default constructor
C
Object cannot be created
Analysis & Theory
If no constructor is defined, PHP automatically uses a default empty constructor.
What can constructors accept as input?
C
Any number of arguments like regular functions
Analysis & Theory
Constructors can accept any number and type of arguments to initialize object properties.
How do you pass values to a constructor when creating an object?
A
Inside the class definition
B
By using object->method()
C
By passing them in parentheses after `new ClassName()`
D
By using object:method()
Analysis & Theory
Values are passed to the constructor using parentheses when creating an object, like `new ClassName('value')`.
Which of the following correctly defines a constructor?
```
class Car {
function __construct($brand) {
echo "Brand is $brand";
}
}
```
D
Constructors cannot have parameters
Analysis & Theory
This is the correct syntax for defining a constructor with one parameter.
Can a class have multiple constructors with different signatures in PHP?
B
No, PHP does not support multiple constructors
Analysis & Theory
PHP does not support method overloading like Java. Only one `__construct()` is allowed, but you can simulate it using optional parameters.
What is the output?
```
class Test {
function __construct() {
echo "Constructor called";
}
}
$t = new Test();
```
Analysis & Theory
When `$t = new Test();` is executed, the constructor runs automatically and outputs `Constructor called`.
Can the constructor be declared as `private` in PHP?
B
Yes, to prevent direct object creation (Singleton pattern)
D
Only with static classes
Analysis & Theory
Yes, constructors can be private to prevent direct object creation, commonly used in Singleton patterns.