【问题标题】:How can I redeclare the same class method more than once in php? [closed]如何在 php 中多次重新声明同一个类方法? [关闭]
【发布时间】:2013-02-11 10:50:08
【问题描述】:

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

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

我遇到的问题是在循环中,它声明了一个驻留在类中的方法。现在因为它正在处理来自数据库的数据,如果事物的数量超过一个,我会收到“类已声明”错误。

有什么方法可以解决这个问题,还是有其他方法可以使用?

【问题讨论】:

  • 有一种方法可以解决这个问题:停止在循环中声明/包含类。顺便说一句,您实际上并没有在这里展示。

标签: php html database class


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你应该做的不是像上面那样创建对象,而是定义一个静态函数来获取你想要的数据。您可以在不创建对象的情况下调用如下函数。

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

    使用循环创建对象是不可接受的。 Read more

    【讨论】:

      【解决方案3】:

      这是创建类的正确方法:

      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 关键字,然后再次尝试执行您的脚本。

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2013-08-21
          • 1970-01-01
          • 2020-12-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-09
          • 2014-01-04
          相关资源
          最近更新 更多