Sergio
Sergio

Reputation: 28837

How to make a "return" end function inside function?

If function alfa calls function beta, how would I make a return statement inside function beta end function alfa?

For example:

function alfa() {
    beta();
    return ('message 2');
}

function beta() {
    return ('message 1');
}

When running echo alfa($x) I want the function to stop and return just message 1.
But I want the return beta (); to be ignored and code continue in case beta() has no return. How to do that?

Upvotes: 0

Views: 179

Answers (4)

Vijaya Pandey
Vijaya Pandey

Reputation: 4282

If you want return beta() to be ignored if return is true and to continue if return is false, this might help you:

 <?PHP

function alfa() {
   if(! beta() ){      
     return ('code continue since beta has no return');
   } else {
       return beta();
   }
}

function beta() {
    return ('beta has return');
}
$x = alfa();
echo $x;

?>

Upvotes: 1

SAVAFA
SAVAFA

Reputation: 818

Do this:

function alfa() {
//code...
return beta ();
}

UPDATE:

Do this:

function alfa() {
   $beta=beta ();
   if(!empty($beta)){
      return $beta;
   }else{
     //code...
   }
}

Upvotes: 2

Dory Zidon
Dory Zidon

Reputation: 10719

either test the return value from the inner function (preferred) or throw an exception:

test return value and signal parent what to do:

function alfa() {
  var retVal = beta();
  return (retVal) ? retVal : ('message 2');
}

throw an exception (not 100% valid, but will work as a hack)

function alfa()
{
 try {
   beta();
   return('message 2'); 
 }
 catch (err)
 {
   return err;
 } 
}  

function beta()
{
   throw 'message 1';
}   

Upvotes: 1

imulsion
imulsion

Reputation: 9040

Return function beta() from alpha():

function alfa() {
//code...    
return beta ();
}

Upvotes: 2

Related Questions