PHP之可变函数

@爱耍流氓的唐僧  August 18, 2020

1.匿名函数/闭包函数(Closure)

$add = function (int $a,int $b):int {
            return $a + $b;
       };

PHP7可以定义参数和返回值类型,具体如上

2.可变函数
方法一:

$add = function (int $a,int $b) {
            return $a + $b;
        };
function multi(int $a,int $b):int
{
    return $a * $b;
}
//
$m1 = 10;
$m2 = 20;
$sum = $add($m1,$m2);
echo "$m1 + $m2 = $sum".PHP_EOL;

$add = "multi";
$mul = $add($m1,$m2);
echo "$m1 * $m2 = $mul".PHP_EOL

方法二:

$add = function (int $a, int $b = 2): int {
              return $a + $b;
       };
$multi = function (int $a, int $b): int {
             return $a * $b;
        };
        // 调用匿名函数
$m1 = 10;
$m2 = 20;
$sum = $add($m1, $m2);
echo "$m1 + $m2 = $sum" . PHP_EOL;
// 将 multi 赋值给 $add
$add = $multi;
$mul = $add($n1, $n2);
echo "$m1 x $m2 = $mul" . PHP_EOL;

闭包中上下文变量的引用,使用关键字use,具体如下

<?php
$m1 = 1;
$m2 = 3;

// 计算两数相加
$add = function () use ($m1, $m2) {
    return $m1 + $m2;
};

// 计算两数相乘
$multi = function () use ($m1, $m2){
    return $m1 * $m2;
};

// 调用匿名函数
$sum = $add();
echo "$m1 + $m2 = $sum" . PHP_EOL;
$mul = $multi();
echo "$m1 x $m2 = $mul" . PHP_EOL;

添加新评论