如何在同一页面上多次使用一个函数?

How Can I use a function multiple times on the same page?

说这段代码:

 <?php while($user=mysqli_fetch_array($resultuser)){ ?>
 <?php 

   function my_function($variable) {
      //do something here...
    }
 ?>
<?php };?>

这显然会return这个错误

Cannot redeclare my_function() previously declared

如果有人需要在同一个页面上多次使用同一个功能怎么办?有没有办法生成随机 function() 名称?知道如何解决这个问题吗?谢谢

用实际代码编辑

    <?php while($deposit26=mysqli_fetch_array($resultdeposit26)){ ?>
<td  data-th="Hours">
    <?php 
        $week1hours = $deposit26['hours_worked'];
        $week2hours = $deposit26['hours_worked_wk2'];
        function time_to_decimal($time) {
        $timeArr = explode(':', $time);
        $decTime = ($timeArr[0] + ($timeArr[1]/60) + ($timeArr[2]/3600));
        return $decTime;
        }
        $groupd26hours = time_to_decimal($week1hours) + time_to_decimal($week2hours);
        echo round($groupd26hours, 2);
     ?>
</td>
  <?php };?>

您想在循环外声明函数并在

调用它
<?php 
  function my_function($variable) {
  //do something here...
}

while($user=mysqli_fetch_array($resultuser)){ 
  my_function($variable);
}?>
<?php 
// Earlier in the file or included with include or require
function time_to_decimal($time) {
        $timeArr = explode(':', $time);
        $decTime = ($timeArr[0] + ($timeArr[1]/60) + ($timeArr[2]/3600));
        return $decTime;
} ?>

...

    <?php while($deposit26=mysqli_fetch_array($resultdeposit26)) : ?>
    <td  data-th="Hours">
    <?php 
        $week1hours = $deposit26['hours_worked'];
        $week2hours = $deposit26['hours_worked_wk2'];
        $groupd26hours = time_to_decimal($week1hours) +   time_to_decimal($week2hours);
        echo round($groupd26hours, 2); ?>
    </td>
    <?php endwhile ?>

让我尝试解释一下我认为可能有所帮助的内容。我认为一个好的起点是考虑在需要函数逻辑的文件中包含一个脚本或一次包含一个脚本。这样多个文件就可以利用相同的逻辑而不必重复。例如:

<?php 
// File functions.php
function my_function($variable) {
  ...  
} 
?>

<?php
// File one
include_once "functions.php"

...
// Use my_function() from file one
my_function($var);
?>

<?php
// File two
include_once "functions.php"

...
// Use my_function() from file two
my_function($var);
?>