【发布时间】:2013-05-01 21:11:24
【问题描述】:
我研究这个问题已经有一段时间了,终于找到了我的答案。
我有三个将输出不同值的数组键。每个键的条件要么为真,要么为 NULL,这就是我为我的数组测试的内容,很简单,看起来像这样。
$a = array();
$a['Font'] = logix::templateParams('googleWebFont');
$a['Font2'] = logix::templateParams('googleWebFont2');
$a['Font3'] = logix::templateParams('googleWebFont3');
例如,我想根据所有三个键的共同条件创建输出 如果一个键为空,那么输出会有所不同,那么如果我有 2 个键“NULL”。我设法创建了一个简单的开关,它涵盖了我需要覆盖我的代码的值范围,如下所示。
$a = array();
$a['Font'] = logix::templateParams('googleWebFont');
$a['Font2'] = logix::templateParams('googleWebFont2');
$a['Font3'] = logix::templateParams('googleWebFont3');
switch (TRUE){
// No font selected
case $a['Font'] == NULL && $a['Font2'] == NULL && $a['Font3'] == NULL:
echo 'nothing';
break;
// First googlefont selected only
case $a['Font'] && $a['Font2'] == NULL && $a['Font3'] == NULL:
echo 'one';
break;
// Second googlefont selected only
case $a['Font2'] && $a['Font'] == NULL && $a['Font3'] == NULL:
echo 'two';
break;
// Third googlefont selected only
case $a['Font3'] && $a['Font2'] == NULL && $a['Font'] == NULL:
echo 'three';
break;
// and Continues to cover another 10 more states.......
到目前为止,这工作正常,涵盖了我需要涵盖的每个可能的变化。我想知道是否有更灵活的方法来做到这一点。例如,如果我想添加另一个数组值并比较集体的条件,那么这个解决方案不够灵活,无法做到这一点。我将不得不完全重写开关的情况,尽管这是不可避免的,是否有更有效的方法来做到这一点。我对 PHP 完全陌生,但我在 OOP 上读过一点,我只是想知道这样做的 OOP 方式是什么。为了更清楚我想要实现的目标。
// 1. collect the array keys
// 2. evaluate keys and check for certain conditions
// 3. output based on conditions
有更灵活的方法吗?
问候
w9914420
【问题讨论】:
标签: php arrays oop function switch-statement