在方法参数中强制使用数组键
P粉006977956
P粉006977956 2024-01-29 14:55:32
0
2
458

所以我的类中有一个方法,它将创建一个新的潜在客户,其中有一个 $fields 参数,用户可以在字段中传递该参数。

假设我有以下格式:

$new_pardot = new FH_Pardot();
$new_pardot->create_prospect();

create_prospect() 方法有 $fields 参数,需要传入一个数组,因此示例如下:

$new_pardot->create_prospect([
    'email' => $posted_data['email'], // Make key mandatory or throw error on method.
    'firstName' => $posted_data['first-name'],
    'lastName' => $posted_data['last-name'],
]);

有没有办法使 $fields 中的 email 密钥成为强制?用户需要传递 email 密钥,但他们可以选择传递其他密钥,如上所示。

这里是示例方法:

public function create_prospect(array $fields)
{
    // Other logic in here.
}

P粉006977956
P粉006977956

全部回复(2)
P粉019353247

您应该为您的 $posted_data['email']. 创建一个验证并检查它是否是必需的。 但如果你想要这种格式,你可以尝试以下方法:

1- 对电子邮件使用单独的参数:

public function create_prospect($email,array $fields)
{
    // Other logic in here.
}

2-更好的方法是检查数组中的电子邮件字段,无论是否有外部函数:

public function create_prospect(array $fields)
{
    if(!array_key_exists("email", $fields)){
        // printing error! => echo 'error' or throw an exception
        return;
     }
}
P粉668146636

您可以采用多种方法中的一种来进行验证。两种明显的方法是在 create_prospect 函数内进行验证,或者在调用 create_prospect 之前/外部进行验证。

传统方法是在尝试创建实体之前进行验证。它使收集和显示验证错误比从各个地方抛出验证消息更容易。

以内

public function create_prospect(array $fields)
{
    if (!isset($fields['email']) {
        throw new ValidationException('Please provide an email');     
    }

    ... carry on with your work
}

之前/之外

$fields = [
    'email' => $posted_data['email'],
    'firstName' => $posted_data['first-name'],
    'lastName' => $posted_data['last-name'],
];

if (!isset($fields['email']) {
    throw new ValidationException('Please provide an email');     
}

$new_pardot = new FH_Pardot();
$new_pardot->create_prospect($fields);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!