3

我有条件包含但遇到了问题。

例如,这有效

<?php if($t==3)
echo 'Foo';
    else
echo 'Foo something else';
    ?>

这:不起作用

<?php if($t==3)
echo 'Foo';
include ('/home/path/public_html/includes/foo_one.php');
echo 'Example: one';
    else
echo 'Foo something else';
include ('/home/path/public_html/includes/foo_two.php');
echo 'Example: two';
 ?>

你能解释一下我做错了什么吗?

或者我应该在包含中包含回声,然后只做 echo include ...blah else echo another include ...

4

4 回答 4

12

{}当您的块内的块if/else超过一行时,您需要使用。

<?php
if($t==3){
    echo 'Foo';
    include ('/home/path/public_html/includes/foo_one.php');
    echo 'Example: one';
}
else{
    echo 'Foo something else';
    include ('/home/path/public_html/includes/foo_two.php');
    echo 'Example: two';
}
?>

无论如何你都应该使用{}它,它使阅读更容易,并防止这样的错误。

于 2012-05-02T21:08:38.487 回答
3

您缺少用于在 if else 中对多行进行分组的 { }:

<?php

if ($t==3) {

  // run all of this is $t equals 3
  echo 'Foo';
  include ('/home/path/public_html/includes/foo_one.php');
  echo 'Example: one';

} else {

  // otherwise, run this
  echo 'Foo something else';
  include ('/home/path/public_html/includes/foo_two.php');
  echo 'Example: two';

}

// runs every time
echo "test me, I always run";

?>
于 2012-05-02T21:10:39.873 回答
1
<?php
if($t==3)
{
  echo 'Foo';
  include ('/home/path/public_html/includes/foo_one.php');
  echo 'Example: one';
}
else
{
  echo 'Foo something else';
  include ('/home/path/public_html/includes/foo_two.php');
  echo 'Example: two';
}
?>
于 2012-05-02T21:08:52.807 回答
0

接受的答案是 100% 正确的,但是......

不必在任何地方都使用花括号 {}。此代码可能看起来像

if ($t==3):
    // code
else:
    // code
endif;

所以需要:关闭endif

于 2015-08-04T13:37:59.753 回答