开发者

Multiple Method Signatures For A Single Abstract Function/Abstract Overloading

开发者 https://www.devze.com 2023-01-30 12:15 出处:网络
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 destinatio

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:

abstra开发者_开发问答ct 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消