php 函数作为数组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9443762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:50:14  来源:igfitidea点击:

Function as array value

phparraysfunctionfunction-pointers

提问by user784446

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!

谢谢!

回答by rodneyrehm

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

回答by Paulo Rodrigues

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

PHP 支持变量函数的概念,因此您可以执行以下操作:

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

Yout can check more examples in manual.

您可以在手册中查看更多示例。

回答by Ibrahim Azhar Armar

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

查看 PHP 的call_user_func. 考虑下面的例子。

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.

plus 数组可以保存任何数据类型,可以是函数调用、嵌套数组、对象、字符串、整数等。

回答by Treffynnon

Yes, you can:

是的你可以:

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

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

当然,这确实需要 PHP匿名函数支持,该支持随 PHP 5.3.0 版一起提供。但是,这会给您留下非常不可读的代码。