Return value

Return value คือ ผลลัพธ์ที่ฟังก์ชันส่งกลับไปให้กับส่วนที่เรียกใช้ฟังก์ชันนั้น

Example

ในภาษา PHP, Java, C, และ Python

<?php
function add($x, $y) {
    return $x + $y;
}

$result = add(5, 10);
echo $result;  // Output: 15
?>

ข้อดี/ข้อเสีย

ข้อดี

  • ยืดหยุ่นในการใช้ เพราะ PHP เป็นภาษาสคริปต์ที่มีความยืดหยุ่นสูง สามารถ return ค่าใด ๆ ออกมาก็ได้

  • ช่วยในการจัดการผลลัพธ์ได้ดี สามารถนำค่าที่คำนวณหรือประมวลผลได้ส่งกลับไปยังส่วนต่าง ๆ ของโปรแกรมได้

ข้อเสีย

  • ข้อจำกัดเรื่องชนิดข้อมูลเพราะไม่มีการกำหนดชนิดข้อมูลที่ชัดเจนในฟังก์ชันของ PHP อาจเกิดข้อผิดพลาดจากการ return

  • หากการ return ค่าเป็น array หรือ object ขนาดใหญ่จะใช้หน่วยความจำมากทำให้โปรแกรมทำงานช้า

วิธีใช้เรียกใช้

จะยกตัวอย่างฟังชั่น greet(name) จะเห็นได้ว่าเราส่ง parameter ที่ชื่อว่า name เข้าไปและตัวโปรแกรมจะต้องคืนค่าออกแบบดังตัวอย่างต่อไปนี้

สรุป

ในทุกภาษา ฟังก์ชัน greet(name) ถูกออกแบบให้รับชื่อเป็นพารามิเตอร์ และ return หรือแสดงข้อความทักทาย

#Reference

  • W3Schools

https://www.w3schools.com/php/keyword_return.asparrow-up-right

https://www.w3schools.com/java/ref_keyword_return.asparrow-up-right

  • PHP: Returning values - Manual

https://www.php.net/manual/en/functions.returning-values.phparrow-up-right

  • Oracle Java Documentation

https://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.htmlarrow-up-right

  • javatpoint.com

https://www.javatpoint.com/return-statement-in-javaarrow-up-right

  • geeksforgeeks.org

https://www.geeksforgeeks.org/return-statement-in-c/arrow-up-right https://www.geeksforgeeks.org/c-function-argument-return-values/arrow-up-right

  • CProgramming.com

https://www.cprogramming.com/arrow-up-right

  • Python Documentation - Defining Functions

https://docs.python.org/3/library/functions.htmlarrow-up-right

https://docs.python.org/3/tutorial/controlflow.html#defining-functionsarrow-up-right

Last updated