【问题标题】:Return with no value in PHP [closed]在PHP中返回没有值[关闭]
【发布时间】:2019-11-05 06:18:09
【问题描述】:

我是 PHP 和 JavaScript 的初学者,对“无价值返回”有疑问。

  1. #codeA#codeB 意思一样吗? 我想知道“函数内部没有值的返回”的作用。

  2. #codeB#codeC 有什么区别吗? 我想知道 "return""exit" 之间是否有区别,在示例代码中。

  3. 如果 #codeB#codeC 具有相同的功能,哪种格式优先于另一种?

  4. “1、2、3”的答案在 JavaScript 中是否相同?

代码A

function doFunction() {
 if(!conditionA) {
 //do something
 }
}

代码B

function doFunction() {
 if(conditionA) return;
 //do something
}

代码C

function doFunction() {
 if(conditionA) exit;
 //do something
} 

【问题讨论】:

  • "codeC" 在 JavaScript 中不起作用,因为没有 exit 语句。
  • codeA 不返回任何内容,codeB 返回 null,codeC 退出 PHP,之后什么都不能执行。

标签: javascript php return


【解决方案1】:

回答你

  1. 在您的有限示例中,它们可能在功能上是等效的,所以是的,它们具有相同的含义(见下文)
  2. return 退出函数作用域,Exit 结束 PHP 执行(见下文)
  3. 见第 1 号(见上文,然后见下文)
  4. 没有JS不是PHP,例如没有“退出”

下面:

很多不同之处在于之后发生的事情,例如:

代码A

function doFunction() {
 if(!conditionA) {
     //do something -- only runs when conditionA is false
 }else{
    //do something else -- only runs when conditionA is true
 }

  //do something something else -- runs rather true or false
  //this could be before
}

 doFunction();
//do something something something else  -- runs rather true or false

代码B

function doFunction() {
 //do something something else --  runs rather true or false

 if(conditionA) return;
 //do something -- only runs when conditionA is false
 //do something else -- only runs when conditionA is false

}

 doFunction();
//do something something something else  -- runs rather true or false

代码C

function doFunction() {
 //do something something else --  runs rather true or false

 if(conditionA) exit;
  //do something -- only runs when conditionA is false
  //do something else -- only runs when conditionA is false
} 

 doFunction();
//do something something something else  -- only runs when conditionA is false

所以从有限的角度来看,它们是相同的,但是当conditionA is false 时,B 什么也不做。而对于 C,如果它是真的,你的脚本就会结束,如果不是,那么它会在执行退出函数 do something something something else 后继续。

至于用哪一种,视情况而定。

【讨论】:

  • 感谢您的回答。我想这是一个非常混乱的问题,很多减号……阅读您的 cmets 后,现在一切都清楚了。我真的很感激你!
猜你喜欢
  • 2012-03-23
  • 2020-06-30
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 2012-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多