
这种代码不仅冗长,而且难以维护。以下介绍两种减少这种重复代码的方法。
首先,分析类的属性,将相关的属性分组到单独的对象中。例如,可以将用户的一些基本信息,联系方式等分别封装到 ProfileData 和 ContactData 类中。
class ProfileData
{
private string $image;
private int $backgroupColor;
public function __construct(string $image, int $backgroupColor) {
$this->image = $image;
$this->backgroupColor = $backgroupColor;
}
}
class ContactData
{
private array $emailAddresses;
private array $phoneNumbers;
public function __construct(array $emailAddresses = [], array $phoneNumbers = []) {
$this->emailAddresses = $emailAddresses;
$this->phoneNumbers = $phoneNumbers;
}
}
class OtherData
{
// ...etc.
}然后,在 User 类的构造函数中,使用这些对象作为参数。
class User
{
private ProfileData $profileData;
private ?ContactData $otherData;
private ?OtherData $contactData;
public function __construct(
ProfileData $profileData,
ContactData $contactData = null,
OtherData $otherData = null
) {
$this->profileData = $profileData;
$this->contactData = $contactData;
$this->otherData = $otherData;
}
public function getProfileData() : ProfileData {
return $this->profileData;
}
// ...etc.
}这种方法可以减少构造函数的参数数量,使代码更清晰。
如果类的构造函数仍然需要大量的参数,可以考虑使用构建器模式。构建器模式允许您逐步构建对象,并提供设置可选参数的方法。
立即学习“PHP免费学习笔记(深入)”;
首先,创建一个 UserBuilder 类,该类的构造函数只接受必需的参数。
class UserBuilder
{
private ProfileData $profileData;
private ?ContactData $contactData;
private ?OtherData $otherData;
public function __construct(ProfileData $profileData) {
$this->profileData = $profileData;
}
public function setContactData(?ContactData $contactData) : UserBuilder {
$this->contactData = $contactData;
// return $this to allow method chaining
return $this;
}
public function setOtherData(?OtherData $otherData) : UserBuilder {
$this->otherData = $otherData;
// return $this to allow method chaining
return $this;
}
public function build() : User {
// build and return User object
return new User(
$this->profileData,
$this->contactData,
$this->otherData
);
}
}然后,使用 UserBuilder 类来创建 User 对象。
// usage example
$builder = new UserBuilder(new ProfileData('path/to/image', 0xCCCCC));
$user = $builder->setContactData(new ContactData(['<a class="__cf_email__" data-cfemail="10797e767f507568717d607c753e737f7d" href="/cdn-cgi/l/email-protection">[email protected]</a>']))
->setOtherData(new OtherData())
->build();为了更方便地使用构建器模式,可以在 User 类中添加一个静态的构建器构造函数。
class User
{
public static function builder(ProfileData $profileData) : UserBuilder {
return new UserBuilder($profileData);
}
}
// usage example
$user = User::builder(new ProfileData('path/to/image', 0xCCCCC))
->setContactData(new ContactData(['<a class="__cf_email__" data-cfemail="0e676068614e6b766f637e626b206d6163" href="/cdn-cgi/l/email-protection">[email protected]</a>']))
->setOtherData(new OtherData())
->build();通过将相关的属性分组到对象中,并使用构建器模式,可以有效地减少PHP类构造函数中的重复代码,提高代码的可读性和可维护性。这些方法可以帮助开发者编写更清晰、更易于维护的代码。
以上就是PHP构造函数中减少变量定义重复代码的技巧的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号