Junior — Middle
What is the best way to pass parameters to an object: through constructor parameters or by assigning them after object creation inside the constructor?
sobes.tech AI
Answer from AI
It is better to pass parameters to an object through the constructor. This allows you to set all necessary properties immediately upon object creation, making the code more readable and preventing the creation of objects in an inconsistent state.
For example:
class User {
private $name;
private $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
}
$user = new User('Ivan', 'ivan@example.com');
If parameters are assigned after creating the object, there is a risk of forgetting to set important properties, which can lead to errors. Using a constructor also makes code maintenance and testing easier.