dsaeyrq451928 2015-10-06 06:28
浏览 70
已采纳

(如果)语句在从另一个php文件中包含它时不起作用

I have two php files first is sample.php and the second is if.php. I have some code written in sample.php basically declaration of two variables and an else statement. I have the if statement in if.php file which I'm including before else statement. But on running my code its shows an error:

Unexpected 'else'...etc.

Can you please help me figuring out what is wrong with the code?

Sample.php

<?php
$a=10;
$b=20;

include 'if.php';
else
{
echo $b.' is greater';
}
?>

if.php

<?php
if($a>$b)
{
echo $a.' is greater';
}
?>
  • 写回答

2条回答 默认 最新

  • dongqi19827 2015-10-06 06:36
    关注
    include 'if.php';
    else
    

    Nice, there is no such thing as include else. Even if you have an if clause at the end of your included file, the include line breaks its sequence.

    else can only come after either an if or an else if block, no third option. Period.

    Here is how PHP parser will see your 2 files

    if($a>$b){
      echo $a.' is greater';
    }
    include "if.php";
    else {
      echo 'na';
    }
    

    Which is clearly invalid.

    If you still want to keep things as they are, like you mentioned in the comments. You can do 1 small trick (amongst many other methods). Make your else another if which is contrary to the first if. Like

    if.php

    if($a>$b){
      echo $a.' is greater';
    }
    

    main file

    include "if.php";
    if($a<=$b) {
      echo 'na';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算