1

I have the following code:

<?php
echo $_SERVER['HTTP_HOST'];
// CONFIGURATION ITEMS
$captcha_private_key = '';
$captcha_public_key = '';
switch ($_SERVER['HTTP_HOST']) {
    case 'earth-neighbours.com' || 'www.earth-neighbours.com':
        $captcha_private_key = '6Lcb_t4SAAAAALkdH4njSny2HYbrmGKS_G84kM_d';
        $captcha_public_key = '6Lcb_t4SAAAAAPEtqJEcWXuo0zmRD5PxYkXx84R4';
        echo 'live';
        break;
    case 'earth-neighbours.projects.mi24.net':
        $captcha_private_key = '6Lca_t4SAAAAAJb5L4sA7fEHxDFA0Jl8jFw-h3hE';
        $captcha_public_key = '6Lca_t4SAAAAAFd-Q2k8esFa9U8nQ2rirEZHFtAH';
        break;
    case 'earth-neighbours.local':
        $captcha_private_key = '6LcZ_t4SAAAAAGc1_S9ahxo-Vg-e7QgHg4yAWBVU';
        $captcha_public_key = '6LcZ_t4SAAAAAPHQDb_f-g4mS6mpmc0heustHQ60&hl';
        echo 'local';
        break;
}
?>

It's running on the local server (earth-neighbours.local) so should output 'local'. Instead it outputs 'live'. The echo at the top however (echo $_SERVER['HTTP_HOST'];) returns the url earth-neighbours.local so it should be 'local' that is echoed. This has me stumped. I had it working before and now I've shifted it to the top of the page and it doesn't work. Weird! Anyone?

4

2 回答 2

3

PHP 不像其他编程语言那样做 switch case 或语句。

当您编写以下内容时:

 switch ($test) {
   case 1 || 2:
    $blah();
    break;
 }

这就是实际发生的情况:

 switch ($test) {
   if (true == $test) {
   }
 }

发生这种情况的原因是案例内容实际上被评估了,并且在 PHP 中,1 || 2 === true. 然后 PHP 对 $test 进行类型转换为布尔值,并且 $test 除非为空,否则结果为真。

PHP“正确”的语法是:

switch ($test) {
  case 1:
  case 2:
    $blah();
    break;

在 PHP(实际上还有一些其他语言)中,一旦解释器switch进入break. 在案件结束时不打破告诉它继续。

于 2013-04-06T20:26:27.103 回答
0

利用:

case 'earth-neighbours.com':
case 'www.earth-neighbours.com':

代替:

case 'earth-neighbours.com' || 'www.earth-neighbours.com':

因为这是switch 语句的错误语法

于 2013-04-06T20:23:53.737 回答