Skip to main content

เนื้อหาภาษาไทย / Thai content

System guide Content reviewed

ฟังก์ชัน: Return Type Declaration

บทความนี้กล่าวถึง **Return Type Declaration** ใน PHP ซึ่งเป็นการกำหนดชนิดข้อมูลที่ฟังก์ชันจะส่งกลับ เพื่อให้โค้ดชัดเจนและน่าเชื่อถือยิ่งขึ้น โดยการกำหนด Return...

ฟังก์ชัน: Return Type Declaration

ในบทเรียนก่อนหน้า เราได้เรียนรู้เกี่ยวกับการสร้างฟังก์ชัน การส่งค่า Parameter และ Argument รวมถึงความแตกต่างระหว่าง Pass by Value และ Pass by Reference ในบทนี้ เราจะมาเรียนรู้เกี่ยวกับการกำหนด Return Type Declaration ซึ่งเป็นคุณสมบัติที่ช่วยให้โค้ดของเรามีความชัดเจนและน่าเชื่อถือมากยิ่งขึ้น

Return Type Declaration คืออะไร?

Return Type Declaration คือการกำหนดชนิดข้อมูล (Data Type) ที่ฟังก์ชันจะส่งกลับ (Return) เมื่อการทำงานของฟังก์ชันเสร็จสิ้น โดยเราจะระบุชนิดข้อมูลที่ต้องการหลังเครื่องหมาย colon (:) ต่อจากส่วนหัวของฟังก์ชัน

รูปแบบการใช้งาน:

function functionName(parameter1: dataType1, parameter2: dataType2): returnType {
  // โค้ดภายในฟังก์ชัน
  return value;
}
  • functionName: ชื่อของฟังก์ชัน
  • parameter1, parameter2: Parameter ที่ฟังก์ชันรับเข้ามา พร้อมระบุ Data Type
  • returnType: ชนิดข้อมูลที่ฟังก์ชันจะส่งกลับ
  • value: ค่าที่ฟังก์ชันส่งกลับ (ต้องเป็นชนิดข้อมูลเดียวกับ returnType)

ตัวอย่างการใช้งาน Return Type Declaration

ตัวอย่างที่ 1: ฟังก์ชันที่คืนค่าเป็น Integer

function add(int $a, int $b): int {
  return $a + $b;
}

$result = add(5, 3); // $result มีค่า 8
echo $result; // แสดงผล 8

ในตัวอย่างนี้ ฟังก์ชัน add รับ Parameter $a และ $b เป็น Integer และกำหนด Return Type เป็น Integer (: int) ฟังก์ชันนี้จะคืนค่าผลรวมของ $a และ $b ซึ่งเป็น Integer เช่นกัน

ตัวอย่างที่ 2: ฟังก์ชันที่คืนค่าเป็น String

function greet(string $name): string {
  return "Hello, " . $name . "!";
}

$greeting = greet("Alice"); // $greeting มีค่า "Hello, Alice!"
echo $greeting; // แสดงผล Hello, Alice!

ฟังก์ชัน greet รับ Parameter $name เป็น String และกำหนด Return Type เป็น String (: string) ฟังก์ชันนี้จะคืนค่าเป็นประโยคทักทายที่ประกอบด้วยคำว่า "Hello, " ตามด้วยชื่อที่ส่งเข้ามา และเครื่องหมาย exclamation mark

ตัวอย่างที่ 3: ฟังก์ชันที่คืนค่าเป็น Boolean

function isEven(int $number): bool {
  return $number % 2 === 0;
}

$isEven = isEven(4); // $isEven มีค่า true
echo var_dump($isEven); // แสดงผล bool(true)

ฟังก์ชัน isEven รับ Parameter $number เป็น Integer และกำหนด Return Type เป็น Boolean (: bool) ฟังก์ชันนี้จะคืนค่า true หาก $number เป็นเลขคู่ และคืนค่า false หากเป็นเลขคี่

ตัวอย่างที่ 4: ฟังก์ชันที่คืนค่าเป็น Array

function getEvenNumbers(array $numbers): array {
  $evenNumbers = [];
  foreach ($numbers as $number) {
    if ($number % 2 === 0) {
      $evenNumbers[] = $number;
    }
  }
  return $evenNumbers;
}

$numbers = [1, 2, 3, 4, 5, 6];
$even = getEvenNumbers($numbers); // $even มีค่า [2, 4, 6]
print_r($even); // แสดงผล Array ( [0] => 2 [1] => 4 [2] => 6 )

ฟังก์ชัน getEvenNumbers รับ Parameter $numbers เป็น Array และกำหนด Return Type เป็น Array (: array) ฟังก์ชันนี้จะคืนค่าเป็น Array ที่ประกอบด้วยเลขคู่ทั้งหมดที่อยู่ใน Array ที่ส่งเข้ามา

ประโยชน์ของการกำหนด Return Type

  1. ช่วยให้โค้ดอ่านง่ายขึ้น: การกำหนด Return Type ทำให้ผู้อ่านโค้ดเข้าใจได้ง่ายขึ้นว่าฟังก์ชันนั้นมีจุดประสงค์อะไร และคาดหวังว่าจะได้ค่าอะไรกลับมา
  2. ช่วยลดข้อผิดพลาด: PHP จะตรวจสอบว่าค่าที่ฟังก์ชันส่งกลับตรงกับ Return Type ที่กำหนดหรือไม่ หากไม่ตรงกัน PHP จะแสดง Warning หรือ Error (ขึ้นอยู่กับการตั้งค่า strict_types) ทำให้เราสามารถตรวจจับข้อผิดพลาดได้ตั้งแต่เนิ่นๆ
  3. ปรับปรุงคุณภาพโค้ด: การกำหนด Return Type เป็นส่วนหนึ่งของการเขียนโค้ดที่มีคุณภาพ (Clean Code) และช่วยให้การบำรุงรักษาโค้ดเป็นไปได้ง่ายขึ้น

การจัดการกับ Error เมื่อ Return Type ไม่ตรงกับที่กำหนด

เมื่อค่าที่ฟังก์ชันส่งกลับไม่ตรงกับ Return Type ที่กำหนด PHP จะจัดการกับ Error ที่เกิดขึ้นแตกต่างกันไป ขึ้นอยู่กับการตั้งค่า strict_types

1. strict_types=0 (ค่าเริ่มต้น):

ในโหมดนี้ PHP จะพยายามแปลงค่าที่ส่งกลับให้เป็นชนิดข้อมูลที่กำหนดไว้ (Type Coercion) หากไม่สามารถแปลงได้ PHP จะแสดง TypeError

function multiply(int $a, int $b): int {
  return $a * $b;
}

$result = multiply(2.5, 3); // Parameter $a ถูกแปลงเป็น int(2)
echo $result; // แสดงผล 6

function divide(int $a, int $b): int {
  return $a / $b;
}

$result = divide(5, 2); // ส่งกลับ float(2.5) -> จะถูกแปลงเป็น int(2) โดยตัดทศนิยมทิ้ง
echo $result; // แสดงผล 2

ข้อควรระวัง: การที่ PHP พยายามแปลงชนิดข้อมูลให้เองอาจทำให้เกิดผลลัพธ์ที่ไม่คาดฝันได้

2. strict_types=1:

ในโหมด Strict Type Checking PHP จะไม่อนุญาตให้มีการแปลงชนิดข้อมูลโดยอัตโนมัติ หากค่าที่ส่งกลับไม่ตรงกับ Return Type ที่กำหนด PHP จะแสดง TypeError ทันที

ในการเปิดใช้งาน Strict Type Checking เราต้องใส่คำสั่ง declare(strict_types=1); ไว้ที่บรรทัดแรกของไฟล์ PHP

<?php
declare(strict_types=1);

function multiply(int $a, int $b): int {
  return $a * $b;
}

try {
    $result = multiply(2.5, 3); // Fatal error: Uncaught TypeError: Argument 1 passed to multiply() must be of the type int, float given
    echo $result;
} catch (TypeError $e) {
    echo "Error: " . $e->getMessage();
}


function divide(int $a, int $b): int {
  return $a / $b;
}

try {
    $result = divide(5, 2); // Fatal error: Uncaught TypeError: Return value of divide() must be of the type int, float returned
    echo $result;
} catch (TypeError $e) {
    echo "Error: " . $e->getMessage();
}

?>

คำแนะนำ: ควรเปิดใช้งาน Strict Type Checking (declare(strict_types=1);) เสมอ เพื่อให้โค้ดมีความน่าเชื่อถือและป้องกันข้อผิดพลาดที่อาจเกิดขึ้นจากการแปลงชนิดข้อมูลโดยอัตโนมัติ

Return Type ของ Void

ในบางกรณี ฟังก์ชันอาจไม่มีการส่งค่าใดๆ กลับคืนมา ในกรณีนี้ เราสามารถกำหนด Return Type เป็น void ได้

function displayMessage(string $message): void {
  echo $message;
}

displayMessage("Hello, World!"); // แสดงผล Hello, World!

ฟังก์ชันที่กำหนด Return Type เป็น void จะไม่สามารถ return ค่าใดๆ ได้ หากพยายาม return ค่าใดๆ PHP จะแสดง Error

Return Type ของ Nullable

บางครั้ง ฟังก์ชันอาจคืนค่าเป็น null ได้ ในกรณีนี้ เราสามารถกำหนด Return Type เป็น Nullable ได้ โดยใช้เครื่องหมาย question mark (?) นำหน้าชนิดข้อมูล

function findUser(string $username): ?string {
  // สมมติว่าเราค้นหา user ในฐานข้อมูล
  if ($username === "admin") {
    return "Administrator";
  } else {
    return null;
  }
}

$user = findUser("admin");
if ($user !== null) {
  echo "User found: " . $user; // แสดงผล User found: Administrator
} else {
  echo "User not found.";
}

$user = findUser("guest");
if ($user !== null) {
  echo "User found: " . $user;
} else {
  echo "User not found."; // แสดงผล User not found.
}

ในตัวอย่างนี้ ฟังก์ชัน findUser อาจคืนค่าเป็น String (ชื่อ User) หรือ null หากไม่พบ User ที่มีชื่อตรงกับที่ระบุ

สรุป

การกำหนด Return Type Declaration เป็นส่วนสำคัญของการเขียนโค้ด PHP ที่มีคุณภาพ ช่วยให้โค้ดอ่านง่าย ลดข้อผิดพลาด และทำให้การบำรุงรักษาโค้ดเป็นไปได้ง่ายขึ้น ควรเปิดใช้งาน Strict Type Checking (declare(strict_types=1);) เสมอ เพื่อให้โค้ดมีความน่าเชื่อถือมากยิ่งขึ้น

ในบทต่อไป เราจะมาเรียนรู้เกี่ยวกับ Variable Scope ซึ่งเป็นเรื่องสำคัญในการทำความเข้าใจว่าตัวแปรต่างๆ สามารถเข้าถึงได้จากส่วนใดของโค้ดบ้าง

Office.in.th Custom Service

Want to build or adapt a system from this structure?

Office.in.th designs and develops enterprise web applications, API integrations, and public- and private-sector management systems, with long-term support.

See our software development service