我有一个Account
具有默认构造函数的类:
class Account {
AccountType $type;
AccountLabel[] $labels;
AccountAttribute[] $attributes;
// Initializes a new account and assigns labels to the new account.
public function __construct(
AccountType $type,
AccountLabel[] $labels,
AccountAttribute[] $attributes)
{
$this->type = $type;
$this->labels = $labels;
$this->attributes = $attributes;
}
// Other parts of the class are omitted here.
}
我需要为此类实现一个复制构造函数,以便可以通过从另一个帐户复制数据来构造一个新帐户。
在其他 OOP 语言中,这可以通过为默认构造函数创建重载来接收帐户类的另一个实例进行复制。但是,PHP 不允许有两个具有相同名称的函数,无论参数是否不同,包括__construct()
函数。
我不能将$labels
参数设为可选,因为它实际上是创建新帐户所必需的。仅添加新参数使其成为可选可能会导致许多误报测试结果。所以,这个实现应该是最后的手段:
class Account {
AccountType $type;
AccountLabel[] $labels;
AccountAttribute[] $attributes;
// Initializes a new account and assigns labels to the new account;
// Or, copy from another account.
public function __construct(
AccountType $type,
AccountLabel[] $labels,
AccountAttribute[] $attributes,
Account $that)
{
if ($that === null) {
$this->type = $type;
$this->labels = $labels;
$this->attributes = $attributes;
} else
{
// Copy from another account.
$this->type = $that->type;
$this->labels = $that->labels;
$this->attributes = $that->attributes;
}
}
// Other parts of the class are omitted here.
}
我也知道神奇的__clone
回调函数。但是,我正在寻找实现复制构造函数的方法,而不是解决方法。