在PHP中正确实现虚拟功能? [英] Correct Implementation of Virtual Functions in PHP?

查看:71
本文介绍了在PHP中正确实现虚拟功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的工作场所(仅适用于php),我们有一个用于数据库抽象的基类.当您要将新的数据库表添加到基层时,必须创建该基类的子类,并重写一些方法来定义使用此表的单独行为.正常行为应保持不变.

现在,我在公司看到许多新的程序员,他们只是重写默认行为的方法.有些人是如此好",可以放入所有默认行为,然后在自己喜欢的地方添加一些单独的东西,而另一些人则试图使用基类及其继承者而自杀.

我解决这个问题的第一个想法是考虑应该由继承类覆盖的抽象方法.但是除了其他反对抽象方法的论点之外,抽象"只是没有显示为什么为什么不能单独使用基类,并且为什么应重写这些功能.

经过一番探索,我没有找到在php中实现真实"虚拟函数的好答案(只是存在一个虚拟函数,几乎扼杀了所有具体实现的希望).

那么,您将如何处理此事?

解决方案

在PHP中,所有受 public protected 保护的功能都是虚拟的".您可以通过在 最终 关键字. (或者将它们设为私有,但这可能不是一个好主意).

在基类的设计中,我会想到子类想要影响的行为. 例如,我将创建诸如before_update()和after_insert()之类的空函数.

function after_insert() {
  // Virtual
}

发生更新/插入事件时,哪个基类将调用.

也许是一个is_valid()函数,该函数始终在基类中返回true,并使用注释块描述子类返回false时的后果.

希望这会给您一些启发.

at my working place (php only) we have a base class for database abstraction. When you want to add a new database table to the base layer, you have to create a subclass of this base class and override some methods to define individual behaviour for using this table. The normal behaviour should stay the same.

Now I have seen many new programmers at our company, who just override the method for the default behaviour. Some are so "nice" to put in all the default behaviour and just add there individual stuff where they like it, others kill themself trying to use the baseclass and their inheritor.

My first thought to solve this problem, was thinking about abstract methods that should be overriden by inheriting classes. But beside other arguments against abstract methods, "abstract" just does not show why the baseclass can't be used by its own and why these function should be overriden.

After some googling around I didn't find a good answer to implementing "real" virtual functions in php (just that there is a virtual function, that nearly kills all hope of a concrete implementation).

So, what would you do with this matter?

解决方案

In PHP all public and protected functions are "virtual". You can prevent functions from being overriden by prepending the final keyword. (Or by making them private, but this is probably a bad idea).

In the design of the baseclass I would think of behaviors that subclasses would want to affect. I would for example create empty functions like before_update() and after_insert().

function after_insert() {
  // Virtual
}

Which the baseclass will call when an update/insert event occurs.

Maybe an is_valid() function which always returns true in the baseclass, and use the commentblock to describe what the consequences are when a subclass return false.

Hopefully this would give you some inspiration.

这篇关于在PHP中正确实现虚拟功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆