Comparing ASP to PHP Includes

September 10, 06 by kenrich

When comparing PHP scripts to Active Server Pages, there is a huge difference between the way you use include files. When using ASP, you either have to use Server-Side Includes or the Server.Execute statement to include one script inside another. In PHP, you have a lot more options. You can use “include”, “require” or “require_once” to include a file.

One of the shortcomings of Server-Sidie includes is that you cannot include a file more than once. This causes problems when you want to do a conditional include. In most cases, you will only need to include a filie once. One case where you might want to include a file twice is an admin login check. With such a script, you would check to see if the user is logged in and if not, you would display the login form. Because you want to include a header and footer in the login include and also include the header and footer on any admin page that includes the login check, you will need to include the header and footer twice.

If you declare any variables, constants, classes or functions in the header or footer, you won’t be allowed to include the file more than once. This would give you a “variable already declared” error. Even if the code is contained in a conditiona “if-then” statement, the parser will still process all of the code statements and recognize the duplicate variable declaration. You could used the Server.Execute statement but when you do this, the file is not truly included within the context of the current script. Instead, the script is executed standalone, and the output from that script is inserted into the current script.

PHP eliminates a lot of these problems by providing truly conditional includes. When you put an include statement within an “If then” statement, the code will not be processed until the script is evaluated and the condition is met. This eliminates the problem with redeclaring variabels inside header and footer. Additionally, PHP provides a new statement called “require_once”. This statement ensures that an include statement is only included once. Only when the require_once statement is first encountered, does each unique include file get included.

This entry no have comments... but you can be first.

Leave a Reply

You must be logged in to post a comment.