如何在同一页面上多次使用某个功能?

时间:2017-04-09 01:31:35

标签: php function-declaration

说出这段代码:

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

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

这显然会返回此错误

  

无法重新声明先前声明的my_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 };?>

3 个答案:

答案 0 :(得分:1)

你希望在循环外声明函数并在中调用它

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

while($user=mysqli_fetch_array($resultuser)){ 
  my_function($variable);
}?>

答案 1 :(得分:1)

<?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 ?>

答案 2 :(得分:1)

让我试着解释一下我认为有用的东西。我认为一个好的起点是在你需要你的函数逻辑的文件中考虑包含一个脚本或包含一个脚本。这样,多个文件可以利用相同的逻辑,而不必重复。例如:

<?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);
?>