在方法参数中指定数组键

  • 本文关键字:数组 方法 参数 php
  • 更新时间 :
  • 英文 :


所以我在类中有一个方法,它将创建一个新的前景,它有一个$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.
}

您可以采用多种方法中的一种来执行验证。两种明显的方法是在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);

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

1-为email使用单独的参数:

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

2-更好的方法是检查数组中的email字段,是否使用外部函数:

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

最新更新