Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么可以';我在PHP中重载了构造函数,填充PHP属性的最佳方法是什么_Php_Constructor - Fatal编程技术网

为什么可以';我在PHP中重载了构造函数,填充PHP属性的最佳方法是什么

为什么可以';我在PHP中重载了构造函数,填充PHP属性的最佳方法是什么,php,constructor,Php,Constructor,在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

在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() {
    }
}

或任何其他组合

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

我的问题有两个:

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

    • 可以使用func_get_args()检索和检查传递的参数。请注意,PHP甚至不检查参数的数量,因此它可以是
      function foo()
      ,而在内部处理许多参数
    • 使用所谓的fluent接口,即一系列setter,每个setter返回
      $this
      。这就变成了
      Foo::create()->setId(42)->setName('blah')
      ,它几乎和python命名的参数一样可读

    php没有显式类型。如果你不能区分
    \uuu构造($a,$b)
    \uu构造($a,$b)
    (如果它们看起来一样,那是因为PHP也会这么想!),那么构造函数重载就没有什么意义了。你可以一直看看神奇的uu get()和u set()如果您不想继续执行getter和setter,则使用方法。我假定uu get()和u set()是内置函数。虽然我不知道它们的行为,但我将检查它们,而不是重载方法,php使用默认参数,这可以完成与重载java构造函数相同的任务。请阅读手册并查看有关默认参数的部分。另外,调用
    func\u get\u args()
    将返回一个包含所有参数的数组,类似于
    argv
    构造函数。对于接受相同数量参数的多个签名,您可以检查传递的变量类型(int、boolean等),然后相应地进行分支。您的第二点看起来非常有趣!我从来不知道有这样的事情存在。我去看看
    class Foo{
        private $id;
        private $test;
        private $name;
    
        function __construct($id, $test, $name) {
            $this->id=$id;
            $this->test=$test;
            $this->name=$name;
        }
    }