【问题标题】:Implementing static functions in PHP在 PHP 中实现静态函数
【发布时间】:2013-10-23 12:57:39
【问题描述】:

这对所有人来说可能听起来很愚蠢,但我遇到了 PHP 中的静态函数的问题。 PHP 中的 OO 编程还是新手,所以需要一些帮助。

我有一个 DB 类,它处理我的应用程序中的所有连接和 crud 操作功能。我有另一个类扩展 DB 类并使用其中的方法。

     class Database(){

          function db_connect(){
                //body
            }
      }

    /*****The inheritor class*****/  
    class Inheritor extends Database{
         function abcd(){
                  $this->db_connect();         //This works good
          }

     }

但现在我必须在另一个类中使用function abcd(){},因为它执行相同的任务。新类就是这个例子,它也扩展了数据库类:

     class newClass extends Database{

           function otherTask(){
               //Here I need to call the function abcd();
            }
     }

我尝试将function abcd() 设为静态,但随后我无法在类Inheritor 的函数定义中使用this。我也尝试创建数据库类的对象,但我认为这是不允许的,因为它给出了错误。

有人可以建议我实现目标的正确方法吗?

【问题讨论】:

  • 您的newClass 需要扩展Inheritor 而不是Database
  • 这是否也允许我访问Database 方法? @ChristopherMorrissey
  • 听起来newClass 应该是extend Inheritor,或者function abcd 应该是Database 的成员。这是关于对代码和类层次结构进行逻辑分组,如果不知道每个类的真正用途,很难给出任何建议。
  • 如果 newClass 需要访问 Inheritor 中的方法,为什么 newClass 不扩展 Inheritor?或者您可以将共享函数移动到数据库中,以便两个子类都可以访问它们。
  • @coderunner 是正确的

标签: php function oop inheritance static


【解决方案1】:

当你扩展一个类时,新类继承之前的方法。 示例:

Class database{
Method a(){}
Method b(){}
Method c(){}
}
Class inheritor extends database{
//this class inherit the previous methods
    Method d(){}
}
Class newCalss extends inheritor{
    //this class will inherit all previous methods
    //if this class you extends the database class you will not have 
    //the methods d() 

}

【讨论】:

    【解决方案2】:

    您可以简单地扩展 Inheritor 类。这将使您可以访问DatabaseInheritor 方法。

    class NewClass extends Inheritor {
       function otherTask() {
           //...
           $this->abcd();
           //...
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多