PHP 错误帮助在 while 循环


PHP error help on while loop

我不知道如何解决PHP错误。

在下面的代码中,我收到错误:

致命错误:无法重新声明getintro()(之前声明...在第 94 行)

我在下面标记了第 94 行。任何帮助或指导,不胜感激。我的目标是根据数据库的每一行循环出每篇博客文章,只显示部分文本。当它点击链接时,它应该打开完整的博客,并在博客中发表评论.php

    <?php   // retreive post
     include('php/config.php');
    include ('php/function.php');
    dbConnect();
    $blog_query = mysql_query(
    'SELECT * 
    FROM Blog
    ORDER BY DATE DESC');
    while($row = mysql_fetch_array($blog_query)):
    $date = date_create($row['DATE']);
    $str = $row['CONTENT'];
    $ID = $row['ID'];
LINE 94    function getIntro($str, $count = 200) {
        return preg_replace('/'s+?('S+)?$/', '', substr(nl2br($str), 0, $count)) . "   <a href='"blog.php?page={$ID}'" class='"changeColor'">Read more...</a>'n";
        }
        $new_string = getIntro($str);
    ?>
    <div class="post">
        <h2><?php echo $row['TITLE']?></h2>
        <h3><?php echo date_format($date, 'l, F j, Y')?></h3>
        <p><?php echo $new_string?></p>
    </div>
</div>      
<?php endwhile?>    

您的函数是在循环中声明的。将函数声明移出循环。

    <?php   // retreive post
     include('php/config.php');
    include ('php/function.php');
    dbConnect();
    $blog_query = mysql_query(
    'SELECT * 
    FROM Blog
    ORDER BY DATE DESC');
    function getIntro($str, $count = 200) {
        return preg_replace('/'s+?('S+)?$/', '', substr(nl2br($str), 0, $count)) . "   <a href='"blog.php?page={$ID}'" class='"changeColor'">Read more...</a>'n";
    }
    while($row = mysql_fetch_array($blog_query)):
    $date = date_create($row['DATE']);
    $str = $row['CONTENT'];
    $ID = $row['ID'];
    $new_string = getIntro($str);
    ?>
    <div class="post">
        <h2><?php echo $row['TITLE']?></h2>
        <h3><?php echo date_format($date, 'l, F j, Y')?></h3>
        <p><?php echo $new_string?></p>
    </div>
</div>      
<?php endwhile?>    

您是在循环中声明一个函数,因此每次迭代它都会重新声明导致问题的相同函数。我会在循环上方声明函数并在循环中调用该函数。

把你的函数声明拿出来 while 循环!(声明必须在您使用之前!

function getIntro($str, $count = 200) {
        return preg_replace('/'s+?('S+)?$/', '', substr(nl2br($str), 0, $count)) . "   <a href='"blog.php?page={$ID}'" class='"changeColor'">Read more...</a>'n";
        }

将函数定义移出循环,例如将其放在 dbConnect 之前:

function getIntro($str, $count = 200) {
        return preg_replace('/'s+?('S+)?$/', '', substr(nl2br($str), 0, $count)) . "   <a href='"blog.php?page={$ID}'" class='"changeColor'">Read more...</a>'n";
        }