Best way to implement multiple constructors in PHP
Hi everyone! I'm new to PHP and ran into a problem. In other languages, like Java or C++, I can declare multiple constructors with different parameters, and the compiler will choose the right one depending on what I pass. For example:
```java
class User {
String name;
int age;
User(String name) {
this.name = name;
}
User(String name, int age) {
this.name = name;
this.age = age;
}
}
```
But in PHP I can't write two constructors with the same name __construct — I get an error "Cannot redeclare". What should I do? I need to create User class objects in different scenarios: sometimes only with a name, sometimes with a name and age, and sometimes with no parameters at all (with default values).
I tried using an argument
No answers yet.
Log in to leave an answer
Blogs