加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

是否有可能在PHP中链式重载构造函数?

发布时间:2020-12-13 17:40:42 所属栏目:PHP教程 来源:网络整理
导读:这是一个组成的例子,当有很多参数时它会变得更有用. 这将使调用者使用新的Person(“Jim”,1950,10,2)或new Person(“Jim”,datetimeobj).我知道可选参数,这不是我在这里寻找的. 在C#我可以这样做: public Person(string name,int birthyear,int birthmonth,
这是一个组成的例子,当有很多参数时它会变得更有用.

这将使调用者使用新的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;
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读