Tuesday, October 8, 2013

PHP: INCLUDE and REQUIRE command

Hi friends, I am Jakir Patel and today in the series of PHP tutorials we will learn how to include any file into some other file.
            Just like C,C++ and JAVA which includes many inbuilt header files in the program to enhance its usage and reduce the size of actual program code; Similarly, we can also include previous files into our current file to make repetitive code to be included easily.

PHP INCLUDE command:
            This INCLUDE command takes the file name and insert that file’s content into the program code we are currently working on. It works just like header file in C, C++, and JAVA. The main advantage of this command is when there are many web pages having the same menu or content than we can include a single file on every web page code instead of writing the same whole code for each web page. It saves us lots of hectic work and time, to make changes in all web pages.

This is the first file code which we will include in our second file. I saved it with name “inc.php”. Now, create a new file and write a code in it. I have created a file “lude.php”.
As you can see the syntax for including a file is given in this second file named as “lude.php”.
Output of this is:
The magic of this code is that when user sees the code of the web page the whole code from both the files will be displayed together as a single file. INCLUDE command takes all the text from file and copies it into the second file.

PHP REQUIRE command:
            There is one more command which is very much similar to the INCLUDE command. REQUIRE command is also used to include file in code. It is good programming practice to use REQUIRE command instead of INCLUDE command. Now, we will see how the above statement is true by using below program code.
Now, this above code where we have used INCLUDE command and file which we have included does not exist but then also this above code will get executed and print the output.

Now, let’s see this same example by using REQUIRE command.
We have just used REQUIRE command instead of INCLUDE command in above code and now lets see the output.

As we can see the code will get executed but will not provide output as there are errors in the code and therefore it is good to use REQUIRE command instead of INCLUDE command as we will never want our program to run with errors.
            Thanks friends for reading this blog, if you have any doubts or suggestions please comment with it below.

1 comment: