The include and require Functions PHP

The include and require functions take the path to a file. The file is parsed as if it were a stand-alone PHP script. This is similar to the include directive in C and the require directive in Perl. There is a subtle difference between the two functions. When the require function is processed, it is replaced with the file it points to. The include function acts more like a function call.

The difference is most dramatic inside a loop. Imagine having three files you wanted to execute one after the other. You could put an include inside a for loop, and if the files were named something like include1.php, include2.php, and include3.php, you would have no problem. You could just build the name based on a counter variable.

If you used require, however, you would execute the first file three times. That's because on the first time through the loop, the call to require would be replaced with the contents of the file. As said, the difference is subtle but can be very dramatic.

We've taken the definition of the array from the main file and put it into its own file. All the code that matches ways to refer to months with a preferred output form is not necessarily interesting to the main script. It is enough to know that we've included the translation array. This makes the script in a lot easier to understand.

This strategy of modularization will enhance the readability of your code. It gives the reader a high-level view. If more detail is needed, it takes a few clicks to open the included file. But more than enhancing readability, coding in this way tends to help you write reusable code. Today you may use the translation array for a catalog request form, but in a week you may need it for displaying data from a legacy database. Instead of cutting out the array definition, you can simply copy the file.

Included File

** Build array for referencing months
$monthName = array(
1=>"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December",
"Jan"=>"January", "Feb"=>"February",
"Mar"=>"March", "Apr"=>"April",
"May"=>"May", "Jun"=>"June",
"Jul"=>"July", "Aug"=>"August",
"Sep"=>"September", "Oct"=>"October",
"Nov"=>"November", "Dec"=>"December",
"January"=>"January", "February"=>"February",
"March"=>"March", "April"=>"April",
"May"=>"May", "June"=>"June",
"July"=>"July", "August"=>"August",
"September"=>"September", "October"=>"October",
"November"=>"November", "December"=>"December"

Including a File

** Get monthName array
print("Month 5 is " . $monthName[5] . "<BR> ");
print("Month Aug is " . $monthName["Aug"] . "<BR> ");
print("Month June is " . $monthName["June"] . "<BR>");

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

PHP Topics