There are two ways to implement that, one of which is obvious to me: to use Reflection
.
Create a
ReflectionClass
from classA
;Get reflection nearest parent with
ReflectionClass::getParentClass()
method;Get
__invoke()
method reflection of parent class byReflectionClass::getMethod()
method;Use
ReflectionMethod::invokeArgs()
method to call parent method withfunc_get_args()
function to pass current argument list.
However, I'm thinking, that it might be an overkill (!) to use this functionality to make a single function call. So I'm considered another way: old and mighty call_user_func_array()
function with get_parent_class()
function.
Get parent class with
get_parent_class()
function;Get current method name (I was thinking to use
__METHOD__
constant, but it always showing a class prefix, where method is declared) with__FUNCTION__
constant;Call
call_user_func_array()
with method map and passfunc_get_args()
as the second argument.
Solution:
<?php
header('Content-Type: text/plain; charset=utf-8');
class A {
public function __invoke(){
$arguments = implode(', ', func_get_args());
echo __METHOD__, ' arguments: ', $arguments, PHP_EOL;
}
}
class B extends A {
public function __invoke(){
echo __METHOD__, ' actions', PHP_EOL;
$method = array(get_parent_class($this), __FUNCTION__);
$result = call_user_func_array($method, func_get_args());
echo __METHOD__, ' actions', PHP_EOL;
}
}
$test = new B();
$test(1, 2, 3);
?>
Result:
B::__invoke actions
A::__invoke arguments: 1, 2, 3
B::__invoke actions