【问题标题】:Problem inserting parameters into a function将参数插入函数时出现问题
【发布时间】:2010-04-30 07:42:49
【问题描述】:

好的,我正在尝试将参数放入一个这样调用的函数中:

$parameters['function']($parameters['params']);

这是我需要放入的函数和参数:

$parameters['function'] = 'test_error';
$parameters['params'] = array(0 => $txt['sometext'], 1 => 'critical', 2 => true);

test_error 函数有 3 个参数:

  1. 要输出的错误
  2. 字符串值中记录的错误类型(“一般”、“严重”等)。
  3. 是否应回显。

这是我得到的输出: 这是一个测试错误。ArraycriticalArray1

我知道这个函数可以完美运行,但它只给了我从它返回的第一个参数。我在这里用$parameters['params'] 做错了什么??

编辑:这里是函数:

function test_error($type = 'error', $error_type = 'general', $echo = true)
{
    global $txt;

    // Build an array of all possible types.
    $valid_types = array(
        'not_installed' => $type == 'not_installed' ? 1 : 0,
        'not_allowed' => $type == 'not_allowed' ? 1 : 0,
        'no_language' => $type == 'no_language' ? 1 : 0,
        'query_error' => $type == 'query_error' ? 1 : 0,
        'empty' => $type == 'empty' ? 1 : 0,
        'error' => $type == 'error' ? 1 : 0,
    );

    $error_html = $error_type == 'critical' ? array('<p class="error">', '</p>') : array('', '');
    $error_string = !empty($valid_types[$type]) ? $txt['dp_module_' . $type] : $type;

    // Should it be echoed?
    if ($echo)
        echo implode($error_string, $error_html);

    // Don't need this anymore!
    unset($valid_types);
}

【问题讨论】:

  • 那里我已经用函数编辑了。

标签: php function parameters


【解决方案1】:

你可能想要call_user_func_array()。作为第二个参数传递的数组的每一项都将用作函数参数,例如:

call_user_func_array( $parameters['function'], $parameters['params'] );

【讨论】:

  • hmmm,所以没有办法使用这种方法$parameters['function']($parameters['params']);??问题是我希望它用这种方法调用该函数,因为它已经可以很好地处理非错误,所以我宁愿不必更改它,因为它会做更多的工作。
  • 你必须做$parameters['function']($parameters['params'][0], $parameters['params'][1], $parameters['params'][2]);,或者修改函数。
  • 有没有办法设置$parameters['params'] = "all parameters in here"; ???会做这个工作吗?如果是这样,在仍然使用相同的功能设置的情况下应该如何完成。
  • @SoLoGHoST:没有。但我不明白你为什么要这样做; call_user_func_array() 就是这样工作的
【解决方案2】:

见下文。

http://www.php.net/manual/en/function.call-user-func-array.php

<?php
function foobar($arg, $arg2) {
    echo __FUNCTION__, " got $arg and $arg2\n";
}
class foo {
    function bar($arg, $arg2) {
        echo __METHOD__, " got $arg and $arg2\n";
    }
}


// Call the foobar() function with 2 arguments
call_user_func_array("foobar", array("one", "two"));

// Call the $foo->bar() method with 2 arguments
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("three", "four"));
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 2021-12-18
    • 2019-03-08
    • 2013-08-27
    • 2014-07-07
    相关资源
    最近更新 更多