建立及使用函式- <?php
- function Hello() {
- echo "Hello, World!";
- }
- Hello();
- ?>
複製代碼 傳送值至函式中- <?php
- function greet($name) {
- echo "Hello, $name!";
- }
- greet("Alice");
- greet("Bob");
- ?>
複製代碼 具回傳值的函式- <?php
- function add($a, $b) {
- return $a + $b;
- }
- $result = add(5, 3);
- echo "5 + 3 = $result";
- ?>
複製代碼 匿名函式- <?php
- $greet = function($name) {
- echo "Hello, $name!";
- };
- $greet("Alice");
- $greet("Bob");
- ?>
複製代碼 遞迴- <?php
- function f($n) {
- if ($n <= 1) {
- return 1;
- } else {
- return $n * f($n - 1);
- }
- }
- $result = f(5);
- echo "5 的階乘是 $result";
- ?>
複製代碼 |