Function as array value

雨燕双飞 提交于 2019-12-17 18:43:20

问题


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())

Thanks!


回答1:


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));



回答2:


PHP supports the concept of variable functions, so you can do something like this:

function foo() { echo "bar"; }
$array = array('fun' => 'foo');
$array['fun']();

Yout can check more examples in manual.




回答3:


check out PHP's call_user_func. consider the below example.

consider two functions

function a($param)
{
    return $param;
}

function b($param)
{
    return $param;
}


$array = array('a' => 'first function param', 'b' => 'second function param');

now if you want to execute all the function in a sequence you can do it with a loop.

foreach($array as $functionName => $param) {
    call_user_func($functioName, $param);
}

plus array can hold any data type, be it function call, nested arrays, object, string, integer etc. etc.




回答4:


Yes, you can:

$array = array(
    'func' => function($var) { return $var * 2; },
);
var_dump($array['func'](2));

This does, of course, require PHP anonymous function support, which arrived with PHP version 5.3.0. This is going to leave you with quite unreadable code though.



来源:https://stackoverflow.com/questions/9443762/function-as-array-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!