在不影响php中的主函数的情况下,在另一个函数中结束一个函数


End a function inside another function without affect the main function in php

我有一个主函数,里面有另一个函数,它与几个函数密切相关。只要满足某些条件,我就需要终止第二个函数。这本身就来自于这些,比方说,内在功能的结果。那么,我怎么能只终止第二个不影响正在运行的主函数的函数呢。我知道dieexit。然而,这两者终止了整个过程。

function main($string) {
   //some code here...
     function second($content) {
        //more code...
        inner_one($evaluate);
        //need to stop second function if some criteria met here, but the rest of the "main function" should run normally
     }
  //more codes...
}
function inner_one($evaluate) {
  //some evaluation here
  //the result of this function should make "second function" stop or allow running
}

如果我在内部函数中使用dieexit,整个过程都会失败。如何让它发挥作用?

希望您能从这里得到想法。

function main($string) {
    //some code here...
    function second($content) {
         //more codes
         $status=inner_one($evaluate);
         if(!$status)//if your inner_one does not run successfully return false
         {
              return false;
         }
         //write your other codes for second
         //return false if it gets any error
         //more codes
          return true;            
    }
    //more codes...
}
function inner_one($evaluate) {
    //your codes going here
    //if you find some error return false
    ///         ............
    return true;//at the end
}

为此,您可能应该去掉second函数,使其成为外部函数。然后在内部函数中使用return。CCD_ 7和CCD_。通常只用于错误处理,例如当整个应用程序确实需要完全停止时。

不过,对于这个特定的代码,您应该添加一个返回值,以便在需要退出时进行检查。

回想一下,当您编写:时

function foo(){
  // code....
}

定义函数foo。除非调用,否则不会执行此函数,可能以不同的方式编写。直接:

 foo();

或者通过使用PHP(call_user_func)的现有函数,或者通过将函数名分配给变量并将该变量用作函数:

$fun = 'foo';
$fun(); // calls foo

函数定义可能出现在PHP代码中语句有效的任何地方。这意味着代码片段中所写的second是一个函数定义,从程序中的任何其他位置都可以看到。微妙的一点是,只有当main被执行(*)时,该定义才会被启用,而不是在全局范围内(在任何其他函数或类之外)具有该函数定义。

尽管这是一个非常强大的功能,但除非您想确保在使second可用之前执行main,或者如果您想在运行时从second的几个定义中选择一个定义,否则我建议避免将函数定义放在其他函数定义中。

现在,当您调用second时,您的函数将表现为任何其他常规PHP函数,因此只需使用return来表示您希望执行流离开该函数(即,PHP解释器退出该函数,并在调用second后继续运行到下一条指令)。

exitdie实际上是中断PHP脚本执行的指令,并且可以在指令有效的任何地方使用。

实现需求的一个简单方法是让inner_one返回一个可以被解释为布尔值的值——当然,最简单的方法是直接使用布尔值:

function inner_one($evaluate){
  // some computation yielding $some_state 
  if ($some_state == SOME_GOOD_VALUE)
    return true;
  else return false;
}

或者更有效:

function inner_one($evaluate){
  // some computation
  return ($some_state == SOME_GOOD_VALUE);
}

second然后可以根据返回的值,通过遵循类似的算法:

function second(){
  // some computation
  if (inner_one($evaluate)){
    // carry on computation
  }
}

或者,为了避免过多的代码嵌套:

function second(){
  // some computation 
  if (!inner_one($evaluate)) 
    return ;
  // carry on computation 
}

(*)准确地说,任何定义都会在执行流评估后立即启用,这解释了为什么您可以在其他内部编写函数,并拥有这种整洁的机制