012_function.php

<?php

declare(strict_types=1);
function add(int $a, int $b): int
{ //限制参数类型和返回值类型
    return $a + $b;
}
echo add(1, 2) . PHP_EOL;

function hello(string $name): string
{ //限制参数类型和返回值类型
    return "Hello, " . $name;
}
echo hello("zhangsan") . PHP_EOL;

$temp = "hello";
echo $temp("zhangsan") . PHP_EOL; //函数名可以是变量

function add2(int $a, int $b = 1, ...$number_array): int
{ //可变参数
    print_r($number_array);
    return $a + $b;
}
echo add2(1, 2, 3, 4, 5) . PHP_EOL;

function swap_all(&$a, &$b)
{ //引用传递
    $temp = $a;
    $a = $b;
    $b = $temp;
}

function swap_int(int &$a, int &$b)
{ //引用传递
    $temp = $a;
    $a = $b;
    $b = $temp;
}

$a = 1;
$b = 2;
swap_int($a, $b);
echo $a . " " . $b . PHP_EOL;

function addIntegerToArray(array &$array, int $value): void
{ //引用传递
    $array[] = $value;
}
$temp_array2 = [];
addIntegerToArray($temp_array2, 1); //限制这个数组只能存储整数
print_r($temp_array2);

 

posted @ 2025-04-27 14:58  黑山老猫  阅读(4)  评论(0)    收藏  举报