MeLight
MeLight

Reputation: 5575

Skip the rest of the (included) file in PHP

I'm including file inner.php in outer.php, I have a condition in inner.php on which I want to stop executing inner.php but NOT the whole script, i.e. I want to jump to the first line in outer.php after the inclusion of inner.php, and I don't want to wrap all of the code in inner.php in an if statement.

Is there a way to do this otherwise?

Upvotes: 25

Views: 8698

Answers (4)

vartec
vartec

Reputation: 134681

Just do return; or return($value); on top level of the inner.php file.

If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call.

Upvotes: 39

Slava
Slava

Reputation: 2050

Throw an exception on the point where you want to stop

// in inner.php:
// ...some code...

throw new Exception('Error description');

// ...some code which will not always execute...

and catch it in the file where you want to resume

// in outer.php
try {
    include 'inner.php';
} catch (Exception $e) {
    //TODO: add error handling here
}

UPDATE

Unlike using return; as other answers here suggest, using exceptions will break anywhere, even if you're in some function inside inner.php

Upvotes: 3

Ólafur Waage
Ólafur Waage

Reputation: 70001

How about having two files for inner. The first and the second part and place the condition on the second include?

Upvotes: 4

Nick
Nick

Reputation: 6965

You can just call return in your include file, but if you're having to do this then it suggests there is something wrong with your architecture. For example, consider this include file:

<?php
// include.php
echo "This is my include";
return;
echo "This is after the include";

..included on the following page:

<?php
// index.php
include('include.php');

The output you'd get is: This is my include.

Upvotes: 9

Related Questions