菜单

Detailed PHP uses Callable Closure to specify callback types

2017年11月22日 - PHPer

Detailed PHP uses Callable Closure to specify callback types

If a method needs to accept a callback method as a parameter, we can write it like this

<? PHP

Function testCallBack ($callback) {

Call_user_func ($callback);

}

Function callback () {

Echo’Do sth callback’;

}

TestCallBack (‘callback’);

&gt?;

But we don’t know whether the callback method can be called, so we need to do a lot of extra work to check whether this callback method can be called.

Is there a better way to judge if the callback method is callable?

We can use callable to force the specified parameter to be a callback type, so that the callback method must be called.

<? PHP

Function testCallBack ($callback) {

Call_user_func ($callback);

}

Function callback () {

Echo’Do sth callback’;

}

TestCallBack (‘abc’);

&gt?;

After the implementation of warning: Warning: (call_user_func) expects parameter 1 to be a valid callback, function abc’not found or invalid function “name program can perform to treatment within dosth, so you need to do a lot of extra work to check whether this callback method can call.

<? PHP

Function testCallBack (callable $callback) {

Call_user_func ($callback);

}

Function callback () {

Echo’Do sth callback’;

}

TestCallBack (‘abc’);

&gt?;

After the execution, prompted error: TypeError: Argument 1 passed to testCallBack () must be callable program and can not be executed to the dosth internal processing, from the parameter type has done inspection processing, play a protective role.

<? PHP

$f = function () {

Return 100;

};

Function testClosure (Closure $callback) {

Return $callback ();

}

$a = testClosure ($f);

Print_r ($a); //100

Exit;

Therefore, if the parameters of the method are callback methods, callable should be forced to specify the callback type, which can reduce the call errors and improve the quality of the program.

发表评论

电子邮件地址不会被公开。