本文介绍了函数作为数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我似乎找不到任何相关内容,并且想知道是否可以将函数或函数引用存储为数组元素的值.例如
I can't seem to find anything of this, and was wondering if it's possible to store a function or function reference as a value for an array element. For e.g.
array("someFunc" => &x(), "anotherFunc" => $this->anotherFunc())
谢谢!
推荐答案
您可以引用"任何函数.函数引用不是内存中的地址"等意义上的引用.这只是函数的名称.
You can "reference" any function. A function reference is not a reference in the sense of "address in memory" or something. It's merely the name of the function.
<?php
$functions = array(
'regular' => 'strlen',
'class_function' => array('ClassName', 'functionName'),
'object_method' => array($object, 'methodName'),
'closure' => function($foo) {
return $foo;
},
);
// while this works
$functions['regular']();
// this doesn't
$functions['class_function']();
// to make this work across the board, you'll need either
call_user_func($functions['object_method'], $arg1, $arg2, $arg3);
// or
call_user_func_array($functions['object_method'], array($arg1, $arg2, $arg3));
这篇关于函数作为数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!