【发布时间】: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