Tutorial :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?


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);  }  


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


class Servlet{      private $servletVar1 = "Some string";    private $servletVar2 = 2150;      public function html(){       echo "<p>Hello World!</p>";    }    }  


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();  


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.


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.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »