每天学习一点点,成功增加一大步

PHP 笔记:lambdas 和 closures

PHP zhanghui 167℃

前面写过了 PHP 的 linq ,那么与 Linq 相关的 lambdas 表达式也自然的浮出水面,要知道 C# 等语言都已经具有这两个特性。今天观测了一下 PHP 在这方面的发展,其实 PHP也是在 5.3 中有了这么一个东东,只是自己没有注意到,所以平时也要多多关注一下。

1、简单的实例

$i = 12;
$j = 33;
$call = function () use ($i, $j) {
    echo $i . "\r\n";
    echo $j . "\r\n";
    echo ($i + $j) . "\r\n";
};
$call();

2、再来个文字游戏

$a = array('PA' => "Pennsylvania", 'VA' => "Virginia", 'TX' => "Texas");
print_r(array_filter($a,
        function ($v) {
            return $v === "Virginia";
        }
    )
);

3、简单的查找

$a = array('PA' => "Pennsylvania", 'VA' => "Virginia", 'TX' => "Texas");
$st = 'Texas';
$tx = array_filter($a, function($v) use($st) {return $v==$st;});
print_r($tx);
print_r(assert(array_keys($tx) == array('TX')));

4、上一篇中的 linq 实例的数组,现在用 lambdas 来写

$students = array(
    array("name" => "Milan", "surname" => "Gallas", "age" => 20, "Job" => "php Programátor"),
    array("name" => "Amdrea", "surname" => "Novotná", "age" => 17, "Job" => "java Programátor"),
    array("name" => "Honza", "surname" => "Pulkert", "age" => 27, "Job" => "c# Programátor"),
    array("name" => "Nikola", "surname" => "Světnická", "age" => 23, "Job" => "php Programátor"),
    array("name" => "Nikola", "surname" => "Světnická", "age" => 23, "Job" => "php Programátor"),
    array("name" => "Petr", "surname" => "Grůdl", "age" => 31, "Job" => "java Programátor"),
);
print_r(array_filter($students,
        function ($v) {
            return $v['age'] > 23;
        }
    )
);

5、接着第 4 个实例,用 lambdas 和 closures 结合的方式起到上下文的作用

$age = 23;
print_r(array_filter($students,
        function ($v) use($age) {
            return $v['age'] > $age;
        }
    )
);

6、还有一种就是类中的属性方法形式的

class T
{
    private $age = array('age' => 23);
    public function main()
    {
        $students = array(
            array("name" => "Milan", "surname" => "Gallas", "age" => 20, "Job" => "php Programátor"),
            array("name" => "Amdrea", "surname" => "Novotná", "age" => 17, "Job" => "java Programátor"),
            array("name" => "Honza", "surname" => "Pulkert", "age" => 27, "Job" => "c# Programátor"),
            array("name" => "Nikola", "surname" => "Světnická", "age" => 23, "Job" => "php Programátor"),
            array("name" => "Nikola", "surname" => "Světnická", "age" => 23, "Job" => "php Programátor"),
            array("name" => "Petr", "surname" => "Grůdl", "age" => 31, "Job" => "java Programátor"),
        );
        print_r(array_filter($students,
                function ($v) {
                    return $v['age'] > $this->age['age'];
                }
            )
        );
    }
}

看了上面的几个实例有没有眼前一亮的感觉呢,原因 PHP 中还有这么简单的数据集处理方式。

参考文献:https://www.ibm.com/developerworks/cn/opensource/os-php-lambda/index.html

转载请注明:隨習筆記 » PHP 笔记:lambdas 和 closures