在我的MeetingType模型中,我有这个常数:
const EXAMPLE_SHAREHOLDERS_MEETING =
[
'Shareholders meeting',
'Management meeting',
'General meeting',
'Start meeting'
];
在我的控制器中,我从模型中这样调用一个函数:
$topics = MeetingType::get_meeting_type_topics($meetingTypeName);
$meetingTypeName
等于“股东会议”。
如何检查传递的参数是否匹配我的常量数组?这是我正在谈论的功能:
/**
* Define and return MeetingType Topics.
*
* @param string $meetingTypeName
* @return array
*/
public static function get_meeting_type_topics($meetingTypeName)
{
switch (MeetingType::EXAMPLE_SHAREHOLDERS_MEETING) {
case 'Shareholders meeting':
$topics = [
'Opening',
];
break;
case 'Management meeting':
$topics = [
'Aanwezigen / afwezigen',
];
break;
case 'General meeting':
$topics = [
'Opening',
];
break;
case 'Start meeting':
$topics = [
"Uitleg van deze vergadering",
];
break;
}
return $topics;
}
我愿意
class MeetingEntity {
// ...
const SHAREHOLDERS_MEETING = 0;
const MANAGEMENT_MEETING = 1;
const GENERAL_MEETING = 2;
const START_MEETING = 3;
const MEETINGS_TYPES =
[
0 => self::SHAREHOLDERS_MEETING,
1 => self::MANAGEMENT_MEETING,
2 => self::GENERAL_MEETING,
3 => self::START_MEETING,
];
// ...
对于有些习惯于这种模式的原因。特别是在键不是数字而是单词的情况下,这非常有用。
比起您可以使用一些简单的开关:
switch($aMeetingType) {
case MeetingEntity::SHAREHOLDERS_MEETING:
// ....
break;
或更安全一些:
if (array_key_exists($aMeetingType, MeetingEntity::MEETING_TYPES)) {
switch(MeetingEntity::MEETING_TYPES[$aMeetingType]) {
case MeetingEntity::SHAREHOLDERS_MEETING:
// ...
break;
}
} else { // throw
您可以将const EXAMPLE_SHAREHOLDERS_MEETING
重新定义为
const EXAMPLE_SHAREHOLDERS_MEETING =
[
'Shareholders meeting' => 'Opening',
'Management meeting' => 'Aanwezigen / afwezigen',
'General meeting' => 'Opening',
'Start meeting' => "Uitleg van deze vergadering",
];
并且在您的函数中返回类似:
public static function get_meeting_type_topics($meetingTypeName)
{
return MeetingType::EXAMPLE_SHAREHOLDERS_MEETING[$meetingTypeName];
}