Multiple Method Signatures For A Single Abstract F

2019-03-31 05:33发布

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);
}

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?

1条回答
Emotional °昔
2楼-- · 2019-03-31 05:58

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.

Example

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

foo(1, 2, 3);   

Output (codepad)

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.

查看更多
登录 后发表回答