Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Câu lệnh return trong PHP

Giới thiệu

Mục đích của câu lệnh return trong PHP là trả lại điều khiển thực thi chương trình về môi trường gọi nó. Sau khi return, thực thi biểu thức tiếp theo sau cái đã gọi function/module khác.

Nếu return xuất hiện bên trong function, thực thi function hiện tại kết thúc, chuyển điều khiển về môi trường gọi. return có thể có mệnh đề expression tùy chọn. Lúc đó, giá trị expression cũng được trả về cùng với điều khiển.

Nếu gặp trong script included, thực thi script hiện tại kết thúc ngay và điều khiển quay về script include nó. Nếu ở top-level script, thực thi kết thúc ngay, trả điều khiển cho OS.

return trong function

Ví dụ return không giá trị

<?php
function SayHello() {
    echo "Hello World!\n";
}
echo "before calling SayHello() function\n";
SayHello();
echo "after returning from SayHello() function";
?>

Kết quả

before calling SayHello() function
Hello World!
after returning from SayHello() function

return có giá trị

Ví dụ return expression

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

Kết quả (nhập 0)

calling function with argument 0
function returns square of 0 = 0

return trong included file

Ví dụ include có return

// 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";
?>

Kết quả

inside main script
now calling test.php script
inside included script
returns from test.php

Included file return expression

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

Kết quả

inside main script
now calling test.php script
from inside included script
returns from test.php