gpt4 book ai didi

php - 如何在 PHP 中实现复制构造函数?

转载 作者:行者123 更新时间:2023-12-02 00:36:11 25 4
gpt4 key购买 nike

我有一个 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 回调函数。但是,我正在寻找实现复制构造函数的方法,而不是变通方法。

最佳答案

PHP 不支持方法重载,并且不能为一个类创建多个构造函数。

实现所需功能的一种常见方法是实现所谓的“命名构造函数”,它只是一个静态工厂方法:

class Account {

AccountType $type;
AccountLabel[] $labels;
AccountAttribute[] $attributes;

// The regular constructor
public function __construct(
AccountType $type,
AccountLabel[] $labels,
AccountAttribute[] $attributes,
{
$this->type = $type;
$this->labels = $labels;
$this->attributes = $attributes;
}

// A "named constructor" that works similar to a copy constructor
public static copyFrom(Account $account)
{
// Do not re-implement the constructor
return new self($account->type, $account->labels, $account->attributes);
}

// Other parts of the class are omitted here.
}

阅读this article更多示例。

关于php - 如何在 PHP 中实现复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com