บทนำ
วัตถุประสงค์ของคำสั่ง return ใน PHP คือคืนควบคุมการดำเนินการโปรแกรมกลับไปที่สภาพแวดล้อมที่เรียก เมื่อคืนค่าแล้ว การดำเนินการของนิพจน์ที่ตามหลังอันที่เรียกฟังก์ชันหรือโมดูลอื่น
หาก return statement เกิดขึ้นภายในฟังก์ชัน การดำเนินการของฟังก์ชันปัจจุบันจะสิ้นสุด ส่งมอบควบคุมกลับไปที่สภาพแวดล้อมที่เรียก return statement อาจมีนิพจน์ clause เพิ่มเติมหน้ามัน ในกรณีนี้ ค่าของนิพจน์ก็จะถูกคืนค่าพร้อมกับการควบคุม
หากพบในสคริปต์ที่ include การดำเนินการของสคริปต์ปัจจุบันสิ้นสุดทันที และควบคุมกลับไปที่สคริปต์ที่ include มัน หากพบในสคริปต์ระดับบนสุด (top level script) เอง การดำเนินการสิ้นสุดทันที ส่งควบคุมกลับไปที่ OS
return ในฟังก์ชัน
ตัวอย่างต่อไปนี้แสดง return statement ในฟังก์ชัน:
ตัวอย่าง
<?php function SayHello(){ echo "Hello World!\n"; } echo "before calling SayHello() function\n"; SayHello(); echo "after returning from SayHello() function"; ?>
ผลลัพธ์
before calling SayHello() function Hello World! after returning from SayHello() function
return พร้อมค่า
ในตัวอย่างต่อไปนี้ ฟังก์ชันคืนค่าพร้อมนิพจน์:
ตัวอย่าง
<?php function square($x){ return $x**2; } $num=(int)readline("enter a number: "); echo "calling function with argument $num\n"; $result=square($num); echo "function returns square of $num = $result"; ?>
ผลลัพธ์
calling function with argument 0 function returns square of 0 = 0
ในตัวอย่างต่อไปนี้ test.php ถูก include และมี return statement ทำให้ควบคุมกลับไปสคริปต์ที่เรียก:
ตัวอย่าง
//main script <?php echo "inside main script\n"; echo "now calling test.php script\n"; include "test.php"; echo "returns from test.php"; ?> //test.php included <?php echo "inside included script\n"; return; echo "this is never executed"; ?>
ผลลัพธ์
inside main script now calling test.php script inside included script returns from test.php
สามารถมี expression clause หน้า return statement ในไฟล์ที่ include ได้ด้วย ในตัวอย่างต่อไปนี้ test.php ที่ include คืนสตริงให้ main script ที่รับและพิมพ์ค่า:
ตัวอย่าง
//main script <?php echo "inside main script\n"; echo "now calling test.php script\n"; $result=include "test.php"; // returns value echo $result; echo "returns from test.php"; ?> //test.php included <?php $var="from inside included script\n"; return $var; ?>
ผลลัพธ์
inside main script now calling test.php script from inside included script returns from test.php