0

我有以下代码,我不断收到未定义的索引错误,代码在 test5() 上失败,但我找不到错误。

<?php
function test1() {
$vars = [0, 1, 2, 4, 3];
for ($i = 0; $i < count($vars); $i++) {
    print $vars[$i] . "\n";
}
} 

function test2() {
$flavors = ['vanilla', 'pistachio', 'banana', 'caramel', 'strawberry'];
$favorite = 'banana';
foreach ($flavors as $key => $flavor) {
    if ($flavor === $favorite) {
        print $key . "\n";
        break;
    }
}
}

function test3() {
$stuff = ['shoes', 33, null, false, true];
$selected = 0;
foreach ($stuff as $key => $thing) {
    if ($thing == $selected) {
        print $key . "\n";
        break;
    }
}
}

function test4() {
$four = 4;
$five = test4_helper($four);
print "four: $four\n";
print "five: $five\n";
}

function test4_helper(&$arg) {
$return = $arg++;
return $return;
}

function test5() {

$products = [
    'Trek Fuel EX 8' => [
                                            'price' => 2000, 
                                            'quantity' => 1
                                            ],
    'Trek Remedy 9' => [
                                            'price' => 2600, 
                                            'quantity' => 2
                                             ],
    'Trek Scratch 8' => [
                                            'price' => 3500,    
                                            'quantity' => 1
                                            ]
];
$total = 0;

$callback = function ($product, $name) {
            //$total = 0;
            $tax = 1.2;
            $price = $product[$name]['price'];
            $total += ($price * $product[$name]['quantity']) * $tax;
           return $total;
        };

array_walk($products, $callback);

print "$total\n";
}

/* * **********************************

 * *** DO NOT EDIT BELOW THIS LINE ****

 * *********************************** */

$tests = 5;
for ($i = 1; $i <= $tests; $i++) {
$function = "test$i";
print "\n\n==== Test $i ====\n";
$function();
print "==== END of test $i ====\n <br>";
}

这段代码有什么问题?看起来它在测试 5 中失败了

4

2 回答 2

0

PHP 闭包与 JavaScript 的闭包不同,它们不继承父作用域。您需要通过use构造传递任何依赖项。在你的例子中......

$callback = function ($product, $name) use ($total) {
    // etc

http://php.net/manual/functions.anonymous.php#example-166

于 2013-10-03T00:15:24.333 回答
-1

PHP 中的数组是这样定义的:

$products = array(
    'Trek Fuel EX 8' => array(
                          'price' => 2000, 
                          'quantity' => 1
                          ),
    'Trek Remedy 9' => array(
                         'price' => 2600, 
                         'quantity' => 2
                         ),
    'Trek Scratch 8' => array(
                         'price' => 3500,    
                         'quantity' => 1
                         )
);

这意味着您还需要查看$vars = [0, 1, 2, 4, 3];$flavors = ['vanilla', 'pistachio', 'banana', 'caramel', 'strawberry'];修复它们。

于 2013-10-02T23:30:20.803 回答