Search code examples
phpincludequit

Quiting a PHP script within another PHP page


I'm trying to implement caching for a PHP script I'm writing, but I keep running into the following problem. I want the script to be included in other PHP pages, but when I try to pass the cached file and exit the embedded script it exits both the script and the parent page, but doesn't parse the rest of the code on the parent page. See the code below for an example.


index.php

<?php
  echo "Hello World!<br />";

  include("file2.php");

  echo "This line will not be printed";
?>


file2.php

<?php
  $whatever = true;

  if ($whatever == true) {
    echo "file2.php has been included<br />";
    exit; // This stops both scripts from further execution
  }

  // Additional code here
?>


If the above index.php is executed you get the following output:

Hello World! 
file2.php has been included

However, I'm trying to get it to look like this:

Hello World! 
file2.php has been included
This line will not be printed

Solution

  • Just wrap the "additional code here" in an else statement?

    <?php
      $whatever = true;
    
      if ($whatever == true) {
        echo "file2.php has been included<br />";
      } else {
        // Additional code here
      }
    ?>
    

    Otherwise I'm not sure what you're getting at. The exit command always terminates the current execution in whole - not just execution of the current file (for which, there is no command)

    EDIT

    Thanks to comments and posts by PHLAK, tomhaigh, MichaelM, and Mario, I myself learned something today - that you CAN indeed terminate the execution of a single included file w/the return command. Thanks, guys!