Home > Backend Development > PHP Tutorial > When to use return in php?

When to use return in php?

黄舟
Release: 2023-03-11 11:36:01
Original
2686 people have browsed it

I just learned PHP for a few days and I don’t quite understand. return is not used to carry and return a value in function. .

Today I saw someone else in video. In an if statement, echo "xxx" is also followed by return
return is not followed by anything. . .
Why not use break here. . . . .
In what situations is return mostly used?
Please explain it in detail. Please, I am just getting started and I can’t understand a lot of functions. Please explain it in a simple and easy-to-understand way. . .

Functions generally have return. You can not write it. If you write it, you can also write return 1. In fact, there is still a slight difference.

For example

//saier
function a(){
     $b=1;
    return $b;
}
function b(){
    $b=1;
    echo $b;
}
 
echo a();  //  输出1
b();   //输出1
//看起来都是输出1,而且b()好像还更方便,其实不然,如果要用到函数的返回值,b()就不行了
 
echo a()+1;  //输出2
//b();这个就不能实现这种功能,需要进去函数里面改,扩展不方便
Copy after login

I have been unable to do it. I know how to use return but I don’t know when to use it and when not to use it. Can anyone tell me? Why do we need to add return in the following example?

<?php
 class man{   
 private $money=1000;   
 public function show(){     
 return $this->money*0.8;
   }
 }
$a=new man();echo $a->show();?>
Copy after login

return is to return a result to the caller of the function/method.

For example, in your example, calling the show() method will return an integer(800). The place where it is called is equivalent to executing echo 800.

If your function/method is to perform some operations rather than return data, you do not need to return, but generally a Boolean value will be returned to indicate whether the operation is successful or failed so that the process can be carried out at the place where the call is made. control.

return, what is it after your function runs? If there is no return, your function will be empty after running.
For example, function a () {return 1;}
Execute a() and you will get 1
$b = a(); Then $b is equal to 1. If there is no return, then there will be no return value when executing a(), which is empty, then $b will be empty

The above is the detailed content of When to use return in php?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template