Home  >  Article  >  Backend Development  >  Interpretation of return usage in PHP

Interpretation of return usage in PHP

卡哇伊
卡哇伊Original
2020-07-15 17:24:073051browse

Interpretation of return usage in PHP

In most programming languages, the return keyword can return the execution result of a function. The usage of return in PHP is also similar, so it is suitable for beginners. Generally speaking, mastering the usage of return in PHP is also the beginning of learning PHP.

#First of all, it means return; return() is a language structure rather than a function. Parentheses are only needed when the parameters contain expressions. Enclose it. Parentheses are usually not used when returning a variable, which can reduce the burden on PHP.

Basic usage:

a), return expression // Return an expression result

b), return(expr) // Function expression

c), return // Return directly, or return a null value

Note: It is best not to use return($val).

1. If return is executed, the content after the return statement will not be executed;

function add($a,$b){
 return $a+$b;
 return $a*$b;
}
$c = add(5,3);//得到的$c值可以用在程序的其他地方!
echo $c;

Output result: 8, only $a $b is executed, $a*$b is not executed.

2.return It can be a function return value or a null value, depending on the specific usage, for example:

##

function test($a){
if($a>10){
 return "a>10";
}else{
 return "a<10";
}
$b=45;
$c=$b-$a;
echo $c;
}

In this example, when you call this function and give any number, it will return a String, if given a number 9, output the string "a<10" and the code:

#

$b=45;
$c=$b-$a;
echo $c;

将永远不会被执行。

3、关于return的调用。

a.php如下:

<?php
include("b.php");
echo "a";
?>

b.php如下:

<?php
echo "b";
return;
echo "b";
?>

输出结果: ba。 在b.php中的return之后的语句不再执行,a.php中include("b.php")之后的语句依然执行。

a.php如下:

<?php
include("b.php");
echo "a";
?>

b.php如下:

<?php
echo "b";
exit; // 结束整个当前脚本
?>

输出结果:b。

4、return的一个重要作用:返回值

例子1:

function test(){
 $a=array(1,2);
 return $a;
}
$b=test();
print_r($b);

例子2:

function test(){
 $a=array(1,2);
}
$b=test();
print_r($b);

输出结果:例子1正常输出,例子2输出为空。为什么呢?因为如果不在函数rest()里面用return返回值,则函数里面只有过程,而没有结果给rest(),调用该函数的时候当然不会有值输出。当然,我们也可将print_r($b)写进test()里面,直接在函数里打印,但很多时候,我们都会在函数外面调用操作,所以要用return返回一个值给外面。

感谢大家的阅读,希望大家受益良多。

This article is reproduced from: https://blog.csdn.net/fjnjxr/article/details/52512722

Recommended tutorial: "php tutorial"

The above is the detailed content of Interpretation of return usage in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn