使用array_push时的错误-“第一个参数应该是数组" [英] Errors when using array_push -- "First argument should be an array"

查看:133
本文介绍了使用array_push时的错误-“第一个参数应该是数组"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

<?php

function foo($bar) 
{
    global $products; 

    //$products = array();

    $query = 'SELECT p_name FROM 0_products WHERE p_category IN (' . $bar . ')';
    $results = mysql_query($query);

    while($row = mysql_fetch_array($results, MYSQL_ASSOC))
    {
        array_push($products, $row);
        echo 'name pushed, ';
    }
}

require('mysql_ipb_connect.php'); // connect to ipb mysql database

$products = array(); 
foo(5);

?>

当我运行它时,得到以下输出:

When I run it I get the following output:

Warning: array_push() [function.array-push]: First argument should be an array in /home/rgcpanel/public_html/category/category.php on line 14
name pushed,
Warning: array_push() [function.array-push]: First argument should be an array in /home/rgcpanel/public_html/category/category.php on line 14
name pushed,
Warning: array_push() [function.array-push]: First argument should be an array in /home/rgcpanel/public_html/category/category.php on line 14
name pushed, 

如果我取消注释"$ products = array();"那么输出是正确的:

If I uncomment "$products = array();" then the output is correct:

name pushed, name pushed, name pushed, 

为什么会这样?我在函数外部声明$ products数组(因此它是全局的),然后将其指定为函数内部的全局.某事不正确,但我不确定那是什么?

Why is this happening? I declare the $products array outside of a function (so it's global), and then specify it as being a global inside the function. Something is not right, but I'm not sure what that is?

感谢您的建议.

推荐答案

根据注释,$products由包含在函数内的包含文件初始化.这就定义了它对功能的范围,而不是全局范围.因此,您需要在调用include之前使用global $products;.

Per the comments, $products was initialized by an included file which was included inside a function. That defines its scope to the function, rather than globally. So you'll need to use global $products; before calling the include.

function func_that_defined_products() {
  global $products;
  include('file_that_defines_products.php');
}

// Now when called globally later, it will be at the correct scope.


function foo($bar) 
{
    global $products; 
    $query = 'SELECT p_name FROM 0_products WHERE p_category IN (' . $bar . ')';
    // etc...
}

无论如何,我发现使用$GLOBALS['products']而不是global关键字更具可读性.与往常一样,在任何可能的情况下,最好将变量传递给函数而不是全局访问它.

In any case, I find it a little more readable to use $GLOBALS['products'] instead of the global keyword. And as always, wherever possible it is a preferred practice to pass the variable into a function rather than accessing it globally.

// If you can, do it this way
function foo($bar, $products) {
  // $products was a param, and so global is unnecessary
}

但是,如果您的情况是CMS定义的,则您可能会失去这样做的灵活性...

However in your case, if the CMS defines it you may lose the flexibility to do it that way...

这篇关于使用array_push时的错误-“第一个参数应该是数组"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆