我一直在寻找这个问题很长一段时间,并最终创建了我的答案。比较数组键值以确定条件语句的OOP方式?
我有三个数组键会输出不同的值。每个键的条件将是真或NULL,这就是我测试我的数组很简单,看起来像这样。
$a = array();
$a['Font'] = logix::templateParams('googleWebFont');
$a['Font2'] = logix::templateParams('googleWebFont2');
$a['Font3'] = logix::templateParams('googleWebFont3');
我想,如果一个键为null,则输出将是不同的,那么如果我有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的方式是什么。更清楚我想要达到的目标。
// 1. collect the array keys
// 2. evaluate keys and check for certain conditions
// 3. output based on conditions
有没有更灵活的方法来做到这一点?
问候
w9914420
嗨Barmar我不知道你是否可以提供一小段代码,以便我能更好地理解你的概念。 – W9914420 2013-05-08 17:09:42
我不知道你的需要比我的答案中的片段还多。您只需填写所需的所有值,然后按照我的说明访问它。你可能想把它包装在一个函数中。 – Barmar 2013-05-08 18:08:57
嗨Barmar,我明白你的意思,然后我可以在case语句中使用函数输出。谢谢! – W9914420 2013-05-09 21:30:51