The test code
/** * Class ParentCallback */
class ParentCallback
{
/ * * *@param int $a
* @param int $b
* @param int $c
*
* @return int
*/
public static function parentSum(int $a.int $b.int $c)
{
return $a + $b + $c;
}
/ * * *@param int $a
* @param int $b
* @param int $c
*
* @return float|int
*/
public function parentMultiply(int $a.int $b.int $c)
{
return $a * $b * $c; }}/** * Class Callback */
class Callback extends ParentCallback
{
/ * * *@param int $a
* @param int $b
*
* @return int
*/
public static function sum(int $a.int $b)
{
return $a + $b;
}
/ * * *@param int $a
* @param int $b
*
* @return float|int
*/
public function multiply(int $a.int $b)
{
return $a * $b; }}/** * Class Invoke */
class Invoke
{
/ * * *@param int $a
* @param int $b
*
* @return float|int
*/
public function __invoke(int $a.int $b)
{
return $a / $b; }}/ * * *@param int $a
* @param int $b
*
* @return int
*/
function sum(int $a.int $b)
{
return $a + $b;
}
/ * * *@param $callback
* @parammixed ... $parameter * *@return mixed
*/
function do_something(callable $callback.$parameter)
{
return call_user_func($callback.$parameter);
}
Copy the code
Test the sample
/ / closures
$ret = do_something(function ($a.$b){
return $a - $b;
}, 5.6);
printf("Closure test Example: %s\n".$ret);
/ / function
$ret = do_something('sum'.5.6);
printf("Function test Example: %s\n".$ret);
// Static method
$ret = do_something([Callback::class, 'sum'].5.6);
printf("Static method example: %s\n".$ret);
$ret = do_something('\Callback::sum'.5.6);
printf("Static method example: %s\n".$ret);
$ret = do_something([Callback::class, 'self::parentSum'].5.6.7);
printf("Static method example: %s\n".$ret);
$ret = do_something([Callback::class, 'parentSum'].5.6.7);
printf("Static method example: %s\n".$ret);
$ret = do_something([Callback::class, 'parent::parentSum'].5.6.7);
printf("Static method example: %s\n".$ret);
/ / method
$callback = new Callback;
$ret = do_something([$callback.'multiply'].5.6);
printf("Common method example: %s\n".$ret);
// invoke
$invoke = new Invoke;
$ret = do_something($invoke.5.6);
printf("Object invoke example: %s\n".$ret);
Copy the code
The test results
Closure test example: -1 Function test example: 11 Static method example: 11 Static method example: 11 Static method example: 18 Static method example: 18 Common method example: 30 Object invoke example: 0.833333333333Copy the code
Refer to the link
- www.php.net/manual/zh/l…
The original link
- Github.com/guanguans/g…