1

when we use return in PHP on global scope, after return, does execution just stop? or processing will go on?

<?php

if(defined("A")) return;
define("A", true);

echo "Hello";

if(defined("A")) return;
define("A", true);

echo "Hello";
?>
6
  • 3
    execution will go on..you need to use exit to stop the further execution.. Commented Jul 29, 2012 at 7:57
  • 1
    have a read php.net/manual/en/function.return.php Commented Jul 29, 2012 at 8:00
  • 2
    @Mr.Alien wrong. Execution will be stopped Commented Jul 29, 2012 at 8:03
  • @AlexanderLarikov Agreed..but I just gave a basic thing that if he uses return he should exit and btw if you read exit in php manual it says Output a message and terminate the current script Commented Jul 29, 2012 at 8:11
  • 1
    @Mr.Alien But there is possible 2 cases: If called from the global scope, then execution of the current script file is ended. If the current script file was included or required, then control is passed back to the calling file. But in OP's case execution will be stopped. Commented Jul 29, 2012 at 8:16

2 Answers 2

3

If you want to stop a script, you'd better use exit, because return should be only used in functions !

http://php.net/manual/en/function.return.php
http://php.net/manual/en/function.exit.php

In your case, the script will end as said by the documentation : return will also end the execution of an eval() statement or script file

Sign up to request clarification or add additional context in comments.

11 Comments

I'm not responsible for that downvote, but the OP did ask about returning in the global scope. Not in functions.
Yes after many edits, but in first case it was not indicated !
@navnav, have you read his first line? AND have you read the function.exit.php manual page? It says Output a message and terminate the current script and there are number of examples supporting his answer and absolutely matching the question's context.
@JasonWilliams Have you seen his edits? Are you aware of the fact that using return in the main script will stop execution, so although using exit; is a good alternative, it is not vital. My first comment was to his first post. Where he talked about functions.
@navnav Yes but as you said, look my edits, i always say : "If you want to stop a script, you'd better use exit, because return should be only used in functions !" If you engage user to use some native php func everywhere not in the right context, it's not my problem ... ANd yes i make and edit after the post was edited for more clarity !
|
1

Your script will be stopped after first return

As documenation says:

If return is called from within the main script file, then script execution ends

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.