Php 通过数组加载函数时为foreach提供的参数无效
我在应用程序中输入了以下代码:Php 通过数组加载函数时为foreach提供的参数无效,php,arrays,oop,foreach,Php,Arrays,Oop,Foreach,我在应用程序中输入了以下代码: public function generate_function_list($generated){ foreach($generated as $method){ call_user_func($method); } } public function echotest($text){ echo '<p>' . $text . '</p&g
public function generate_function_list($generated){
foreach($generated as $method){
call_user_func($method);
}
}
public function echotest($text){
echo '<p>' . $text . '</p>';
}
这是输出:
<p>testcontainer 1</p><p>testcontainer 2</p><p>testcontainer 3</p><p>testcontainer4</p>
testcontainer 1testcontainer 2testcontainer 3testcontainer 4
是的,正如您所看到的,输出是正确的,它正确地执行了函数及其参数,但不幸的是,我得到以下信息:
警告:为C:\AppServ\www\test\testclassgenerator.php第2行中的foreach()提供的参数无效
我一直在检查generate_函数_list函数中的foreach,我发现我无法读取内部设置的函数,所以有点奇怪
我的意图是使用一个简单的数组以友好的方式调用方法,并给出及时的参数
谢谢 阵列构建不正确的原因示例:
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
的函数将被PHP分配NULL
值
因此,正如您在转储输出中所述,您的数组是一个空数组,每个空数组对应于您在数组中进行的echotest()调用。然后将该数组传递给
generate\u function\u list()
,它将简单地迭代所有这些空值,并执行一系列call\u user\u func(NULL)
调用,这是毫无意义的。foreach需要一个数组。如果得到“invalid argument”,则传递的不是数组的内容,如字符串或数字。因此,在您的方法中执行var\u dump($generated)
并查看传入的内容。我得到的是:{[0]=>NULL[1]=>NULL[2]=>NULL[3]=>NULL}。所有参数似乎都已到达,因为它们都在输出中执行,即使您在输出中看到空值。因此,echotest正在执行输出,而不返回数组定义中捕获的任何内容。这意味着你在做调用用户函数(null)
,这永远不会起作用。产生此错误的实际foreach发生在别处,因为您在generate_function_list.Hello@MarcB中传递一个空数组,那么为什么它会返回正确的输出呢?因为$foo=echo'bar'
没有为$foo
分配任何内容。echo不是函数,它没有返回值。它执行一些输出,然后$foo
变为null。因此,数组中正确地充满了null。调用echo测试,它执行一些输出,然后什么也不返回,这意味着php将null放入数组中。
array(2) {
[0]=> NULL
[1]=> string(3) "bar"
}