作为数组值

use*_*446 13 php arrays function-pointers function

我似乎无法找到任何此类内容,并且想知道是否可以将函数或函数引用存储为数组元素的值.例如

array("someFunc" => &x(), "anotherFunc" => $this->anotherFunc())
Run Code Online (Sandbox Code Playgroud)

谢谢!

rod*_*ehm 14

您可以"参考"任何功能.函数引用不是"内存中的地址"或其他意义上的引用.它只是函数的名称.

<?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));
Run Code Online (Sandbox Code Playgroud)


Pau*_*ues 5

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

function foo() { echo "bar"; }
$array = array('fun' => 'foo');
$array['fun']();
Run Code Online (Sandbox Code Playgroud)

Yout可以在手册中查看更多示例.


Ibr*_*mar 5

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

考虑两个功能

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

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


$array = array('a' => 'first function param', 'b' => 'second function param');
Run Code Online (Sandbox Code Playgroud)

现在,如果你想在序列中执行所有函数,你可以用循环来完成它.

foreach($array as $functionName => $param) {
    call_user_func($functioName, $param);
}
Run Code Online (Sandbox Code Playgroud)

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


Tre*_*non 5

是的你可以:

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

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