admin 發表於 2020-10-21 16:21:31

Functions

<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // 呼叫 the function
?> 結果: Hello world!


admin 發表於 2020-10-21 16:40:25

arguments
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?> 第一個呼叫的結果: Hege Refsnes. Born in 1975 其它以此類推..



admin 發表於 2020-10-21 16:45:30

PHP is a Loosely Typed Language.
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it will return 10
?> 結果: 10



admin 發表於 2020-10-21 17:00:06

<?php declare(strict_types=1); // strict requirement

function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not an integer, an error will be thrown
?> 結果: 錯誤訊息


admin 發表於 2020-10-21 17:05:15

Returning values
<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?> let a function return a value



admin 發表於 2020-10-21 17:07:55

<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?> 結果: 6


admin 發表於 2020-10-21 17:11:57

<?php
function add_five(&$value) {
$value += 5;
}

$num = 2;
add_five($num);
echo $num;
?> 結果: 7


頁: [1]
查看完整版本: Functions