所以我的类中有一个方法,它将创建一个新的潜在客户,其中有一个 $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.
}            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您应该为您的
$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; } }您可以采用多种方法中的一种来进行验证。两种明显的方法是在
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);