【问题标题】:Invalid argument supplied for foreach while loading functions through an array通过数组加载函数时为 foreach 提供的参数无效
【发布时间】:2014-08-08 23:05:14
【问题描述】:

我在我的应用程序中加入了以下代码:

    public function generate_function_list($generated){
        foreach($generated as $method){
            call_user_func($method);
        }
    }
    public function echotest($text){    
        echo '<p>' . $text . '</p>';
    }

我是这样执行的:

    $arrayx = array(
        FormGenerator::echotest("test container 1"),
        FormGenerator::echotest("test container 2"),
        FormGenerator::echotest("test container 3"),
        FormGenerator::echotest("test container 4")
    );

    $nez->generate_function_list($arrayx);

这是输出:

<p>testcontainer 1</p><p>testcontainer 2</p><p>testcontainer 3</p><p>testcontainer4</p>

是的,你可以看到输出是正确的,它正确地执行了函数及其参数,但不幸的是我在下面得到了这个:

警告:在第 2 行的 C:\AppServ\www\test\testclassgenerator.php 中为 foreach() 提供的参数无效

我一直在检查generate_function_list函数中的foreach,发现里面设置的函数看不到,所以有点奇怪。

我的意图是动态地调用方法,使用简单的数组,并提供及时的参数。

谢谢!

【问题讨论】:

  • foreach 需要一个数组。如果你得到“无效参数”,那么你传入的不是数组,比如字符串或数字。所以在你的方法中做一个var_dump($generated),看看到底传递了什么。
  • 我得到的是:{ [0]=> NULL [1]=> NULL [2]=> NULL [3]=> NULL }。似乎已达到所有参数,因为它们都在输出中执行,即使您在那里看到 NULL 值。
  • 所以你的 echotest 正在输出,而不是返回任何将在数组定义中捕获的内容。这意味着你正在做call_user_func(null),这将永远不会起作用。并且产生此错误的实际 foreach 发生在其他地方,因为您在 generate_function_list 中传递了一个空数组。
  • 你好@MarcB,那么为什么它会返回正确的输出?
  • 因为$foo = echo 'bar' 没有为$foo 分配任何东西。 echo 不是函数,它没有返回值。它做了一些输出,然后$foo 变为空。所以你的数组正确地充满了空值。你调用你的 echo 测试,它会做一些输出,然后什么也不返回,这意味着 php 将 null 放入数组中。

标签: php arrays oop foreach


【解决方案1】:

您的数组构建不正确的示例:

function foo() {
   echo 'foo'; // immediate output of 'foo', no return value
}

function bar() {
   return 'bar'; // no output, return 'bar' to the calling context
}


$foo = foo();
$bar = bar();

var_dump($foo); // outputs: NULL
var_dump($bar); // outputs: string(3) "bar"

$array = array(
    foo(),
    bar()
);

var_dump($array);

输出:

array(2) {
  [0]=> NULL
  [1]=> string(3) "bar"
}

您的echotest 执行输出。它没有return 电话。当执行返回到调用上下文时,没有 return 的函数会被 PHP 分配 NULL 值。

因此,正如您在转储输出中所述,您的数组是一个 NULL 数组,对应于您在数组中进行的每个 echotest() 调用。然后将该数组传递给您的generate_function_list(),这将简单地遍历所有这些空值,并执行一系列call_user_func(NULL) 调用,这是毫无意义的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-17
    • 2011-02-07
    相关资源
    最近更新 更多