gpt4 book ai didi

php - 构造函数与太多的获取和设置

转载 作者:可可西里 更新时间:2023-11-01 01:08:05 27 4
gpt4 key购买 nike

我有一个包含 18 个属性的记录类。

在将该类提交到数据库之前,所有 18 个属性都必须具有经过验证的数据。

因为我正在 OOP 化一个工作的程序 web 应用程序,所以我进行了这种倒退。

首先,我介绍了修改现有记录的工作流程。当时,将所有 18 个属性都放入 __construct 方法并避免 setter 的垃圾加载是有意义的。一个单独的 loader 类处理数据库业务,可以返回单个对象或记录对象数组。一切正常。

但后来是时候解决新记录创建工作流程了,突然我需要实例化一个空记录,除了我的记录构造函数是一个需要 18 个参数的饥饿的野兽......

...所以你剥离了构造函数?但是每次我想使用现有记录时,我都必须添加 18 个 setter 并调用它们......

似乎没有太大的改进! :-/

真正的程序员如何处理这个问题? (我只是一个小爱好者......)

最佳答案

任一默认参数都是一个选项,但如果您只想使用第一个和最后一个参数,则必须填写大量空值。

再一次,你可以做数组循环:

private $prop1;
private $prop2;
// more properties here.

function __construct( array $props ) // `array` here is for type-hinting.
{
foreach( array( 'prop1', 'prop2' /*, all of the props for this object */
as $property )
{
// basically, this will assign all of the properties as they exist in the
// props array
if( isset( $props[ $property ] ) )
$this->$property = $props[ $property ];
}
}

或者,如果您想保留旧的构造函数签名:

function __construct( $prop1, $prop2 = NULL, $prop3 = NULL /* ... */ ) 
{
if( is_array( $prop1 ) )
{
$this->array_prop_assignment( $prop1 );
}
else
{
$args = func_get_args();
// this ensures that anything which is passed to the constructor
// will go to the "new" old constructor
call_user_func_array( array( $this, 'param_prop_assignment' ), $args );
}
}

function param_prop_assignment( $prop1, $prop2 /* ... */ )
{
//your old constructor can go here.
}

function array_prop_assignment( array $props )
{
// foreach example above would go here.
}

新版本还为您提供了以下选项:

$k = new DataClass(); // no idea what the real class name is.
$k->param_prop_assignment( 1, 2, 3 /* ... */ );

关于php - 构造函数与太多的获取和设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6756422/

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