PHP包括函数,后跟echo

时间:2016-01-03 14:04:58

标签: php php-include

在这个stackoverflow讨论中,用户告诉我,我可以从外部访问包含目前我在同一.php文件中的代码部分的php。
这是我的file1.php:

     <?php
    $commentsLabels = array('First Signal','Second Signal');
    $commentsTexts = array('First comment for #signal1 id - it will open in a fancybox.','Second comment for #signal2 id - it will open in a fancybox.');       

    $counter = 0; 

     ?>

<!--GENERATING LABELS-->
<div  class="signals"> 
    <ul>

    <?php
    foreach ($commentsLabels as $commentLabel) {
        $counter++;
    ?>
            <li><a href="#signal<?php echo $counter; ?>" class="fancybox"><?php echo $commentLabel; ?></a></li> 
    <?php
        } //loop ends       
    ?>  

    </ul>
</div>

<!--GENERATING POPUPS-->
<?php
    $counter = 0; //reset counter

    foreach ($commentsTexts as $commentText) { //loop starts
        $counter++; 
?>
        <div id="signal<?php echo $counter; ?>" style="display:none;"><p style="color:#fff"><?php echo $commentText; ?></p></div>
<?php
    } //loop ends
?>

我试图进入&#34; file2.php&#34;创建标签和文本的代码部分:

<?php
    $commentsLabels = array('First Signal','Second Signal');
        $commentsTexts = array('First comment for #signal1 id - it will open in a fancybox.','Second comment for #signal2 id - it will open in a fancybox.');       
?>   

然后我创建了一个include函数,后跟echo $变量到file1.php:

<li><a href="#signal<?php echo $counter; ?>" class="fancybox"><?php include 'file2.php'; echo $commentLabel; ?></a></li> 

<div id="signal<?php echo $counter; ?>" style="display:none;"><p style="color:#fff"><?php include 'file2.php'; echo $commentText; ?></p></div>

当我尝试时,它没有显示任何内容:你能告诉我为什么包含功能不起作用吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

File2.php

<?php
     $commentsLabels = array('First Signal','Second Signal');
     $commentsTexts = array('First comment for #signal1 id - it will   open in a fancybox.',
                     'Second comment for #signal2 id - it will open in a fancybox.');       
?>  

File1.php

<?php
     include 'file2.php';
     $counter = 0;
?>
<!--GENERATING LABELS-->
<div  class="signals"> 
  <ul>

  <?php
       foreach ($commentsLabels as $commentLabel) {
       $counter++;
  ?>
     <li><a href="#signal<?php echo $counter; ?>" class="fancybox"><?php    echo $commentLabel; ?></a></li> 
  <?php } ?>  
  </ul>
</div>

<!--GENERATING POPUPS-->
<?php
    $counter = 0; //reset counter

    foreach ($commentsTexts as $commentText) { //loop starts
       $counter++; 
?>
    <div id="signal<?php echo $counter; ?>" style="display:none;"><p style="color:#fff"><?php echo $commentText; ?></p></div>
<?php } ?>