单个抽象函数/抽象重载的多种方法签名 [英] Multiple Method Signatures For A Single Abstract Function/Abstract Overloading

查看:50
本文介绍了单个抽象函数/抽象重载的多种方法签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类,用于将数据从一个数据库移动到另一个数据库,有时创建基本条目所需的数据是不同的,这是由于目标数据库中存在遗留表,其中包括用于定位数据的指令.来源.显然,这是问题所在:

I have an abstract class for moving data from one database to another, and sometimes the data required to create the basic entries is different, due to the presence of a legacy table in the destination database which includes instructions for locating the data in the source. Obviously simplified, here is where the problem comes into play:

abstract class foo
{
    protected abstract function createBaseEntry($id);
}

有时,我只需要向此函数传递一个ID,但在某些情况下,我需要传递两个ID.当然,如果具体方法的实际方法签名与抽象方法不匹配,PHP将引发致命错误并暂停执行.除了使用null预定义最大数量的参数并修改扩展该参数的每个具体类之外,还有什么方法可以解决此问题?

Sometimes, I only need the one ID passed to this function, but in some cases I need to pass two. Of course, if the actual method signature of the concrete method does not match the abstract method PHP will raise a Fatal error and halt execution. Other than predefining with null the maximum number of arguments and modifying every concrete class that extends this one, is there any way to get around this?

推荐答案

您可以使用 func_num_args() ,如果您无法/不想将方法签名更改为具有可选的第二个参数.

You could use func_num_args() and func_get_args() to determine the number of arguments at runtime if you cannot/want not change the method signature to have an optional second argument.

示例

function foo()
{   
    $num  = func_num_args();
    $args = func_get_args();
    var_dump($num, $args);
}

foo(1, 2, 3);   

输出(键盘)

int(3) 
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } 

当签名中定义了参数时,这也将起作用.

This will also work when there are arguments defined in the signature.

这篇关于单个抽象函数/抽象重载的多种方法签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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