相关疑难解决方法(0)

在PHP中,什么是闭包,为什么它使用"use"标识符?

我正在检查一些PHP 5.3.0功能,并在网站上遇到一些看起来很有趣的代码:

public function getTotal($tax)
{
    $total = 0.00;

    $callback =
        /* This line here: */
        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);
}
Run Code Online (Sandbox Code Playgroud)

作为匿名函数的一个例子.

有人知道吗?有文件吗?如果它被使用它看起来很邪恶?

php closures

387
推荐指数
5
解决办法
17万
查看次数

替换字符串中的占位符变量

刚刚完成这个功能.基本上,假设查看字符串并尝试查找任何占位符变量,这些变量将位于两个大括号之间{}.它抓取大括号之间的值,并使用它来查看应与键匹配的数组.然后它用匹配键数组中的值替换字符串中的大括号变量.

但它有一些问题.首先是当var_dump($matches)它把它放在数组中的数组时.所以我必须使用两个foreach()只是达到正确的数据.

我也觉得它很沉重,我一直在寻找它,试图让它变得更好,但我有点难过.我错过了任何优化?

function dynStr($str,$vars) {
    preg_match_all("/\{[A-Z0-9_]+\}+/", $str, $matches);
    foreach($matches as $match_group) {
        foreach($match_group as $match) {
            $match = str_replace("}", "", $match);
            $match = str_replace("{", "", $match);
            $match = strtolower($match);
            $allowed = array_keys($vars);
            $match_up = strtoupper($match);
            $str = (in_array($match, $allowed)) ? str_replace("{".$match_up."}", $vars[$match], $str) : str_replace("{".$match_up."}", '', $str);
        }
    }
    return $str;
}

$variables = array("first_name"=>"John","last_name"=>"Smith","status"=>"won");
$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you {STATUS} the competition.';
echo dynStr($string,$variables);
//Would …
Run Code Online (Sandbox Code Playgroud)

php preg-match

11
推荐指数
3
解决办法
2万
查看次数

标签 统计

php ×2

closures ×1

preg-match ×1