Home  >  Article  >  Backend Development  >  什么时候该用return呢?

什么时候该用return呢?

WBOY
WBOYOriginal
2016-06-06 20:17:332281browse

一直搞不懂return的用法 不知道什么时候该用什么时候不该用 谁能讲讲呢?
下面这个例子为什么要加return呢?

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


?></code>

回复内容:

一直搞不懂return的用法 不知道什么时候该用什么时候不该用 谁能讲讲呢?
下面这个例子为什么要加return呢?

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


?></code>

return就是把一个结果返回给函数/方法的调用者。

比如你的例子调用show()方法就把一个整数(800)返回去。调用的地方就相当于执行了echo 800

如果你的函数/方法是为了执行一些操作而不是为了返回数据,可以不return,但一般都会return一个布尔值来表示操作是成功还是失败以便调用的地方进行流程控制。

return 什么,你的函数运行完就是什么,如果没有return 你的函数运行完就是空的
比如function a () {return 1;}
执行a()就得到1
$b = a(); 那么$b就等于1,如果没有return那么执行a()就没有返回值,也就是空,那$b就是空了

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