1

如何在顶部包含一个包含带有大括号的 if 语句的 php 文件,

然后在底部包含一个文件,该文件包含该 if 语句的右花括号,前面还有更多 if 语句?

<?php include_once('includes/authtop.php');?>

<div id="mydiv">
// stuff here
</div>

<?php include_once('includes/authbottom.php');?>

**Note**: authbottom.php contains several ifelse statements and displays data accordingly.

我需要这样做以获得更干净和有组织的代码,但是当我将代码移动到包含中时出现错误,就好像呈现的页面无法识别用于打开关闭的花括号?

如果它与函数或函数/类有关,请给我一个例子。

这是顶层文件:authtop.php

if( $loggedin ) { 

if( $accessLevel == 0  ) {

这是底部文件:authbottom.php

} elseif() {

// do this

} elseif() {

// do this 

} elseif() {

// do this 

} else {

// do this

}
4

2 回答 2

0

您不应该包含以这种方式处理条件的文件。它混乱且容易出错;正如你所发现的。

相反,重构你的代码。

这是一个例子......

function someFunc() {
   if( $loggedin ) { 

      if( $accessLevel == 0  ) {

        return TRUE;

      } elseif() {

      // do this

      } elseif() {

      // do this 

      } elseif() {

      // do this 

      } else {

      // do this

      }
}



if (someFunc()) {
    // stuff here
}
于 2011-12-16T01:08:32.463 回答
0

I'd use a switch

include('authtop.php);

switch($accesslevel) {
  default:
  case 0: include('filepath.php'); break;
  case 1: include('filepath.php'); break;
  case 2: include('filepath.php'); break;
  case 3: include('filepath.php'); break;
  case 4: include('filepath.php'); break;
}

include('authbottom.php');

or....

switch($accesslevel) {
  default:
  case 0: 
       if($paid==0) { $pd='THANKS'; } else { $pd='DONATE!'; }
       $lvl = 'Guest';
       /* whatever you need to include for level 0 here */
       break;
  case 1:
       if($paid==0) { $pd='THANKS'; } else { $pd='DONATE!'; }
       $lvl = 'User';
       /* whatever you need to include for level 1 here */
       break;
  case 2:
       if($paid==0) { $pd='THANKS'; } else { $pd='DONATE!'; }
       $lvl = 'Moderator';
       /* whatever you need to include for level 2 here */
       break;
  case 3:
       if($paid==0) { $pd='THANKS'; } else { $pd='DONATE!'; }
       $lvl = 'Super Moderator';
       /* whatever you need to include for level 3 here */
       break;
  case 4: 
       if($paid==0) { $pd='THANKS'; } else { $pd='DONATE!'; }
       $lvl = 'Admin';
       /* whatever you need to include for level 4 here */
       break;
}


echo '
<div class="myDiv">'.$pd.'</div>
<div class="myDiv2">'.$lvl.'</div> ';

The HTML will show whatever the $pd variable has been set at according to the switch.

And it's best to set up the include so they are self contained without any open braces or brackets.

于 2011-12-16T01:27:05.050 回答