脚本宝典收集整理的这篇文章主要介绍了是否有可能在PHP中链式重载构造函数?,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
这将使调用者使用新的PErson(“Jim”,1950,10,2)或new Person(“Jim”,datetimeobj).我知道可选参数,这不是我在这里寻找的.
在C#我可以这样做:
public Person(string name,int birthyear,int birthmonth,int birthday) :this(name,new DateTime(birthyear,birthmonth,birthday)){ } public Person(string name,DateTime birthdate) { this.name = name; this.birthdate = birthdate; }
我可以在PHP中做类似的事情吗?就像是:
function __construct($name,$birthyear,$birthmonth,$birthday) { $date = new DateTime("{$birthyear}\\{$birthmonth}\\{$birthyear}"); __construct($name,$date); } function __construct($name,$birthdate) { $this->name = $name; $this->birthdate = $birthdate; }
如果这是不可能的,那么什么是好的选择呢?
class Foo { ... public function __construct($foo,DateTime $bar) { ... } public static function FromYmd($foo,$year,$month,$day) { return new self($foo,new DateTime("$year-$month-$day")); } } $foo1 = new Foo('foo',$dateTimeObject); $foo2 = Foo::fromYmd('foo',2012,2,25);
应该有一个规范的构造函数,但是你可以拥有尽可能多的替代构造函数,这些构造函数都是方便的包装器,它们都引用了规范的构造函数.或者,您可以在通常不在常规构造函数中设置的这些替代构造函数中设置替代值:
class Foo { PRotected $bar = 'default'; public static function wIThBar($bar) { $foo = new self; $foo->bar = $bar; return $foo; } }
以上是脚本宝典为你收集整理的是否有可能在PHP中链式重载构造函数?全部内容,希望文章能够帮你解决是否有可能在PHP中链式重载构造函数?所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。