如何在php中多次重新声明同一类方法


How can I redeclare the same class method more than once in php?

我的代码有问题。我有这样的代码:

<?php
     include('php/SelectHistory.php');
     include('php/SelectSmallHistoryUser.php');
     include('php/SelectSmallHistoryProject.php');
     include('php/SelectSmallHistoryFunctionality.php');
     $newHistoryRow = SelectHistory();
     echo "<table width='100%'>";
     if (count($newHistoryRow) > 0)
     {
         foreach ($newHistoryRow as $current)
         {
              $chosenUser = SelectSmallHistoryUser($current->userID);
              $chosenProject = SelectSmallHistoryProject($current->projectID);
              $chosenFunctionality = SelectSmallHistoryFunctionality($current->functionalityID);
              echo "<tr>";
              echo "<td>" . $chosenUser->fullName . " was busy with " . $chosenFunctionality->functionalityName . " on " . $chosenProject->projectName . " at " . $current->lastModifiedDate;
              echo "</tr>";
              unset($chosenUser);
              unset($chosenProject);
              unset($chosenFunctionality);
          }
      }
      else
      {
          echo "<tr><td>No History To Display.</td></tr>";
      }
      echo "</table>";
?>

我对它的问题是,在循环中,它声明了一个驻留在类中的方法。现在,因为它使用的是数据库中的数据,如果事情的数量超过一个,我会得到一个"Class already declared"错误。

有没有办法解决这个问题,或者有没有其他方法可以使用?

这是创建类的正确方法:

class TestClass {
    public $property;
    //some other properties
    function __construct($id) {
        $this->property=$id;
        //do some other stuff
    }
    //some other functions
}

创建类实例的正确方法是:

 $test = new TestClass($id);

注意__construct()函数和new关键字,然后再次尝试执行脚本。

我想做一个新的。$var = new SelectHistory();

与其像上面那样创建对象,不如定义一个静态函数来获取所需的数据。您可以在不创建对象的情况下调用下面的函数。

SelectSmallHistoryUser::getData($current->userID);

在循环中创建对象是不可接受的。阅读更多

在循环中声明或包含类是不好的。但请检查以下内容:http://www.php.net/manual/en/function.class-exists.php