Multiple Method Signatures For A Single Abstract Function/Abstract Overloading
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.
精彩评论