<?php // Basic function function greet($name) { return "Hello, $name!"; } echo greet("Ko Min"); // "Hello, Ko Min!" echo greet("Ma Aye"); // "Hello, Ma Aye!" // Multiple parameters function add($a, $b) { return $a + $b; } echo add(3, 4); // 7 // No return = null function sayHi() { echo "Hi!"; } ?>
<?php function greet($name = "Guest", $greeting = "Hello") { return "$greeting, $name!"; } greet(); // "Hello, Guest!" greet("Ko Min"); // "Hello, Ko Min!" greet("Ko Min", "Mingalaba"); // "Mingalaba, Ko Min!" // ⚠️ Default params ကို နောက်မှ ထည့်ပါ function bad($a = 1, $b) {} // ❌ Error function good($a, $b = 1) {} // ✅ OK ?>
<?php // Parameter type + return type function add(int $a, int $b): int { return $a + $b; } function greet(string $name): string { return "Hello, $name"; } function calculate(float $price, int $qty): float { return $price * $qty; } // Nullable type function findUser(int $id): ?string { // returns string or null return $id === 1 ? "Ko Min" : null; } // void — no return value function logMessage(string $msg): void { echo $msg; } ?>
<?php $globalVar = "I'm global"; function myFunc() { // PHP မှာ global variable ကို function ထဲ တိုက်ရိုက် မဝင်ရဘူး! echo $globalVar; // ❌ Error/undefined // global keyword သုံးရတယ် global $globalVar; echo $globalVar; // ✅ "I'm global" } // Static variable — function call မှ တိုင်း မ reset function counter() { static $count = 0; $count++; echo $count; } counter(); // 1 counter(); // 2 counter(); // 3 ?>
| Function | ဘာလုပ်တယ် | Example |
|---|---|---|
strlen($s) | String length | strlen("Hello") → 5 |
strtolower($s) | Lowercase | "HELLO" → "hello" |
strtoupper($s) | Uppercase | "hello" → "HELLO" |
count($arr) | Array count | count([1,2,3]) → 3 |
date("Y-m-d") | Current date | "2024-06-01" |
time() | Unix timestamp | 1717200000 |
rand(1,100) | Random number | 42 |
abs(-5) | Absolute value | 5 |
round(3.7) | Round | 4 |
floor(3.9) | Floor | 3 |
ceil(3.1) | Ceil | 4 |
max(1,5,3) | Maximum | 5 |
min(1,5,3) | Minimum | 1 |
<?php // Anonymous function $greet = function($name) { return "Hello, $name!"; }; echo $greet("Min"); // Hello, Min! // Arrow function (PHP 7.4+) $double = fn($n) => $n * 2; echo $double(5); // 10 // Used with array_map, array_filter $numbers = [1, 2, 3, 4, 5]; $doubled = array_map(fn($n) => $n * 2, $numbers); // [2, 4, 6, 8, 10] $evens = array_filter($numbers, fn($n) => $n % 2 === 0); // [2, 4] // Closure use — bring outer variable in $prefix = "Hello"; $greet2 = function($name) use ($prefix) { return "$prefix, $name!"; }; ?>
← PHP 03 | Next: PHP Lesson 05 → Arrays →