将数组值预加载到函数中

时间:2009-11-21 02:22:59

标签: php

我不确定我是否正确执行此操作,使用函数defaultcoindload()预加载硬币的数组值;

defaultcoindload();
function defaultcoindload()
{
/*Have the coin loads up to a maximum of a 1.00 dollar in value:
An associative array-ID key is associated with  value(ID is Nickels with value of 20).
$money = array("Nickels"=>20, "Dimes"=>10, "Quarters"=>10);
The array code for $money above  is  the same as the array code below,
with the difference being the structure and the ID keys can be accessed in a script*/

if ($money < 1.00)
{
echo "money";
}
else if($money = $insertcoins[$selection])
{
echo "$selection";
}


 $money['Nickels'] = "20";
 $money['Dimes'] = "10";
 $money['Quarters'] = "10";
 echo "The value of Nickels is " . $money['Nickels'] ." cents.";

此外,这样做甚至是合法的:

function getselection($selection,$price)
{

在原始函数defaultcoinload()中有另一个函数或多个函数,我认为只需要一点澄清,谢谢你,因为没有燃烧。

1 个答案:

答案 0 :(得分:1)

看起来很好。也许这些陈述的顺序令人困惑?大多数工程师在调用之前会编写函数声明。 (你可以反过来说。)

我关注的两件事:

一个是一个赋值,它看起来像是一个相等的比较更有意义:

if ($money == $insertcoins[$selection])

另一个是$ money不是全局的,所以在函数中分配它不会在它之外做出明显的改变。通过在函数内添加global $money来解决此问题。

总之,请尝试这样做:

function defaultcoindload()
{
    /* Have the coin loads up to a maximum of a 1.00 dollar in value:
     * An associative array-ID key is associated with  value (ID is Nickels with value of 20).
     * $money = array("Nickels"=>20, "Dimes"=>10, "Quarters"=>10);
     * The array code for $money above is the same as the array code below,
     * with the difference being the structure and the ID keys can be accessed in a script
     */
    global $money;

    $money['Nickels'] = 20;
    $money['Dimes']   = 10;
    $money['Quarters'] = 4;
    echo "The value of Nickels is " . $money['Nickels'] ." cents.";
}

defaultcoindload();

我删除了很多看似调试的东西,但在此之后,你可以参考$ money。

print_r($money);  // show all the money

我留下的剩余错误可供您识别和修复。