问题描述
我有模特
BaseUser.class.php
User.class.php
UserTable.class.php
在用户类中我已经覆盖了删除功能
class User extends BaseUser {
function delete(){
}
}
现在,如果我想调用父删除函数....怎么办?
Now, if i want to call parent delete function .... how ?
示例
$user = new User();
$user->delete(); // will call the overridden delete
$user-> ?? ; // want to call parent delete
推荐答案
从技术上讲,这在外部"(公共接口)是不可能的.
Technically this is not possible from the "outside" (the public interface) for good reason.
如果您了解原因(否则请阅读下文),并且您确实知道自己在做什么,那么没有理由不提供该功能:
If you have understood why (otherwise read below), and you actually know what you do, there is no reason to actually not offer the functionality:
class User extends BaseUser {
...
function parentDelete(){
parent::delete();
}
...
}
user = new User();
$user->delete(); // will call the overridden delete
$user->parentDelete(); // want to call parent delete
但是,如果您曾经这样做过,您应该知道您以某种方式滥用了继承.这一定是一种特殊情况,因为我无法想象在任何情况下您实际上都需要这样做.
However if you ever do that, you should know that you have misused inheritance somehow. This must be an exceptional situation as I can not imagine any situation where you actually need that to do at all.
因此,请尝试阐明您需要该功能的原因,以便为自己提供更好的建议.
So try to formulate why you need that functionality so to give yourself better suggestions.
为什么这么糟糕?
原因很简单:在您的软件中,您不需要知道 $user
是否有父级.这是一些你根本不应该关心的细节.
For a very simple reason: In your software you do not need to know that $user
has a parent or not. That is some detail you should not care at all about.
这将允许您稍后将软件中的任何用户对象替换为用户的子对象.这很重要,因为您希望随着时间的推移更改您的软件.
That will allow you to replace any user-object you have in your software with a childobject of user later on. This is important as you want to change your software over time.
如果您将内部细节作为公共界面的一部分,您就是在剥夺自己保持灵活性的可能性.不灵活真的很糟糕.
If you make the internal detail part of the public interface you are robbing yourself the possibility to keep things flexible. Not being flexible is really a bad situation.
这篇关于如何从子实例调用父函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!