为什么不能在PHP中重载构造函数?填充PHP属性的最佳方式是什么?


Why can't I have overloaded constructor in PHP and What is the best way of populating PHP properties

在Java中,我喜欢有1到x个构造函数的灵活性,这取决于我的需要和我的类具有的属性/属性的数量。

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;
    }
}

不像在PHP中,我只能有一个构造函数从我学到的到目前为止。

class Foo{
    private $id;
    private $test;
    private $name;
    function __construct() {
    }
}

class Foo{
    private $id;
    private $test;
    private $name;
    function __construct($id, $test, $name) {
        $this->id=$id;
        $this->test=$test;
        $this->name=$name;
    }
}

或任何其他组合;

我做什么:大多数时候,我更喜欢使用getter和setter来填充这些属性,但这可能会导致为带有一些属性的类编写大量代码。我认为可能有一些更好的方法:

我的问题有两个:

    为什么我不能重载PHP构造函数?我想知道这个限制背后的原因填充PHP对象属性的最佳原因是什么?

两件事:

  • 您可以使用func_get_args()来检索和检查传递的参数。注意,PHP甚至不检查参数的数量,所以它可以是function foo(),而在许多参数被处理。
  • 使用所谓的流畅接口,即每个返回$this的setter链。然后变成Foo::create()->setId(42)->setName('blah'),几乎和python的命名参数一样可读。