Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP return Statement


แนะนำตัว

วัตถุประสงค์ของการ คืนสินค้า คำสั่งใน PHP คือการคืนการควบคุมการทำงานของโปรแกรมกลับไปยังสภาพแวดล้อมที่ถูกเรียก เมื่อกลับมา ให้ดำเนินการนิพจน์ตามหน้าที่เรียกใช้ฟังก์ชันหรือโมดูลอื่น

หากคำสั่ง return เกิดขึ้นภายในฟังก์ชัน การดำเนินการของฟังก์ชันปัจจุบันจะสิ้นสุดลง โดยส่งการควบคุมกลับไปยังสภาพแวดล้อมที่เรียกใช้ คำสั่งส่งคืนอาจมีนิพจน์เป็นส่วนเสริมที่อยู่ข้างหน้า ในกรณีนั้น ค่าของนิพจน์จะถูกส่งกลับนอกเหนือจากตัวควบคุมด้วย

หากพบใน รวม สคริปต์ การดำเนินการของสคริปต์ปัจจุบันจะสิ้นสุดลงทันทีและการควบคุมจะกลับไปที่สคริปต์ที่รวมไว้ หากพบในสคริปต์ระดับบนสุด การดำเนินการจะสิ้นสุดลงทันที โดยส่งการควบคุมกลับคืนสู่ระบบปฏิบัติการ

ส่งคืนในฟังก์ชัน

ตัวอย่างต่อไปนี้แสดงคำสั่ง return ในฟังก์ชัน

ตัวอย่าง

<?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

ผลตอบแทนพร้อมค่า

ในตัวอย่างต่อไปนี้ ฟังก์ชันส่งคืนพร้อมนิพจน์

ตัวอย่าง

<?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 และมี return ststement ทำให้การควบคุมกลับไปใช้สคริปต์การเรียก

ตัวอย่าง

//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

สามารถมีประโยคนิพจน์หน้าคำสั่ง return ในไฟล์ที่รวมไว้ด้วย ในตัวอย่างต่อไปนี้ รวม test.php จะส่งคืนสตริงไปยังสคริปต์หลักที่ยอมรับและพิมพ์ค่า

ตัวอย่าง

//main script
<?php
echo "inside main script\n";
echo "now calling test.php script\n";
$result=include "test.php";
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