最近在研究回调函数,据说是变身高级程序员必备技能之一,网上搜了大半天,到现在一直也没搞清楚回调使用的真正场景,遂在公司的laravel项目中以call_user_func为关键字搜了下,N多回调,没看懂,以下面代码为例:
/**
* Asserts that a haystack that is stored in a static attribute of a class
* or an attribute of an object contains a needle.
*
* @param mixed $needle
* @param string $haystackAttributeName
* @param mixed $haystackClassOrObject
* @param string $message
* @param bool $ignoreCase
* @param bool $checkForObjectIdentity
* @param bool $checkForNonObjectIdentity
*/
function assertAttributeContains($needle, $haystackAttributeName, $haystackClassOrObject, $message = '', $ignoreCase = false, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
return call_user_func_array(
'PHPUnit_Framework_Assert::assertAttributeContains',
func_get_args()
);
}
这段代码使用了回调,但是搞不清楚不能正常的写吗?如下:
function assertAttributeContains($needle, $haystackAttributeName, $haystackClassOrObject, $message = '', $ignoreCase = false, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false)
{
return PHPUnit_Framework_Assert::assertAttributeContains(func_get_args());
}
为何不用这种直接调用而非得用回调呢?感觉有点装逼。
请大神指点,多谢!
5 回答

慕标琳琳
TA贡献1830条经验 获得超9个赞

叮当猫咪
TA贡献1776条经验 获得超12个赞
最近在一个项目中用到多进程,每个进程需要分配一个方法丢给进程执行,这时候就需要将闭包函数作为一个参数传进去,然后在子进程调用!!,由此可知,所有需要把函数或方法作为一个参数让另外一个对象去执行的情况下需要用到闭包函数!

GCT1015
TA贡献1827条经验 获得超4个赞
这个问题有点难回答
首先大部分直接调用都是可以直接调用,而不用call_user_func 和 call_user_func_array
这2个函数, 调用的函数可以是匿名,类对象方法,类的静态方法
Closure匿名类,会在后续很有很多利用的地方
use可引起上下文变量,这是php缺失部分
更多地方,你可以参考php官方

凤凰求蛊
TA贡献1825条经验 获得超4个赞
这里的用法我觉得只是为了简化参数传递的过程,另外,你改写的方法有问题。应该是
return PHPUnit_Framework_Assert::assertAttributeContains(...func_get_args());
在没有...
操作符的PHP版本里面,如果不用call_user_func_array
,那么你就只能手动传递每一个参数。
- 5 回答
- 0 关注
- 518 浏览
添加回答
举报
0/150
提交
取消