Comment

Comment by dmiladinov

In order to use variables from the scope that the anonymous function came from, you have to explicitly import them into the anonymous function with the use[1] block:

    public function getTotal($tax)
    {
        $total = 0.00;
        
        $callback =
            function ($quantity, $product) use ($tax, &$total)
            {
                $pricePerItem = constant(__CLASS__ . "::PRICE_" .
                    strtoupper($product));
                $total += ($pricePerItem * $quantity) * ($tax + 1.0);
            };
        
        array_walk($this->products, $callback);
        return round($total, 2);
    }

In other languages that have true closures, the anonymous function "closes over" the lexical scope in which it was declared.

[1]: http://www.php.net/manual/en/functions.anonymous.php

parent dmiladinov 12 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton