为什么可以';我在PHP中重载了构造函数,填充PHP属性的最佳方法是什么
在Java中,根据我的需要和类拥有的属性/属性的数量,我可以灵活地使用1到x个构造函数为什么可以';我在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
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填充这些属性,但这可能会导致为具有一些属性的类编写大量代码。我认为可以有一些更好的方法:
我的问题有两个:
- 可以使用func_get_args()检索和检查传递的参数。请注意,PHP甚至不检查参数的数量,因此它可以是
,而在内部处理许多参数function foo()
- 使用所谓的fluent接口,即一系列setter,每个setter返回
。这就变成了$this
,它几乎和python命名的参数一样可读Foo::create()->setId(42)->setName('blah')
\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;
}
}