簡體   English   中英

如何在同一頁面上多次使用功能?

[英]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 };?>

這顯然會返回此錯誤

無法重新聲明先前聲明的my_function()

那么,如果有人需要在同一頁面上多次使用同一功能怎么辦? 有沒有一種方法可以生成隨機的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);
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM