abel
abel

Reputation: 2383

PHP equivalent to jsp:include

PHP has include and require_once which are equivalent to JSP's include directive(<%@ include ..%>) JSP also has a jsp:include which only includes the output from the included file, keeping the included file in a servlet of its own.

I am looking for something similar in PHP, so that the main page's variables and other content don't mess with those of the included files. Does one exist?

Upvotes: 0

Views: 1377

Answers (4)

VolkerK
VolkerK

Reputation: 96159

There's Runkit_Sandbox

Instantiating the Runkit_Sandbox class creates a new thread with its own scope and program stack. Using a set of options passed to the constructor, this environment may be restricted to a subset of what the primary interpreter can do and provide a safer environment for executing user supplied code.

But I've never used it and therefore cannot say how reliable it is.

Upvotes: 0

Brad
Brad

Reputation: 163272

You could always do a file_get_contents() and call the URL of that PHP script on your server, and then echo the results. I would caution you though that this is very bad from a security standpoint. If your DNS records get changed and what not, someone could really mess with things. It is best to avoid this problem altogether by using OOP as "thephpdeveloper" suggested. You can also use namespaces.

Upvotes: 1

mauris
mauris

Reputation: 43619

Doing it in OOP manner should also do the trick, in a more neatly manner.

servlet.php

class Servlet{

  private $servletVar1 = "Some string";
  private $servletVar2 = 2150;

  public function html(){
     echo "<p>Hello World!</p>";
  }

}

main.php

include("servlet.php");

class MainPage{

   private $title = "Page Title";

   public function html(){
       echo "<!DOCTYPE html>";
       echo "<html>";
       echo "<head>";
       echo "<title>".$this->title."</title>";
       echo "<head>";
       echo "<body>";
       $servlet = new Servlet();
       $servlet->html();
       echo "</body>";
       echo "</html>";
   }

}


$page = new MainPage();
$page->html();

Upvotes: 1

TJ L
TJ L

Reputation: 24452

An easy solution is to include the file inside a function to prevent the scope of the file from littering the global namespace.

function jsp_include($file) {
    include($file);
}

Upvotes: 1

Related Questions