In Java, I enjoy the flexibility of having 1 to x number of constructors depending my need and the number of properties/attributes my class have.
class Foo{
private int id;
private boolean test;
private String name;
public Foo(){
}
public Foo(int id){
this.id=id;
}
public Foo(boolean test){
this.test=test;
}
public Foo(int id, boolean test){
this.id=id;
this.test=test;
}
}
Unlike in PHP I can only have one constructor from what I have learnt so far.
class Foo{
private $id;
private $test;
private $name;
function __construct() {
}
}
Or
class Foo{
private $id;
private $test;
private $name;
function __construct($id, $test, $name) {
$this->id=$id;
$this->test=$test;
$this->name=$name;
}
}
Or any other combinations;
What I do: Most time I prefer populating these properties using the getters and setters but this can result in writing a lot of codes for classes with some number of properties. I think there could be some better approaches:
My questions are two:
- Why can't I overload PHP constructors? I want to know reason behind this limitation
- What is the best why of populating a PHP object properties?