Functions
<?phpfunction writeMsg() {
echo "Hello world!";
}
writeMsg(); // 呼叫 the function
?> 結果: Hello world!
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 其它以此類推..
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
<?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
?> 結果: 錯誤訊息
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
<?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
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?> 結果: 7
頁:
[1]