How to include a php file in a php program?

Sometimes we may want to include another php file in our php program. This technique is normally followed when let us suppose we want to interact with the database, know for example there are 20 php files in which database interaction code is written, as we all know before interacting with database, we first have to create connection with it, so in the above senario we have to write connection code in all 20 pages one by one, it is really frustrated thing but the really frustrated stuff is that when u wish to change anything in your connection, u will have to also change it in all 20 pages.

So to overcome this problem, file inclusion is used.

Methods to include the file

There are normally four methods to include file in php. These methods are used to include the content of file in your program before server execute it.
  1. include();
  2. include_once();
  3. require();
  4. require_once();

Example:-

include('myfile.php');

include_once('myfile.php');

require('myfile.php');

require_once('myfile.php');

Normally people use include() or require() as these functions working is almost same, the only differ between these is error handling process. Incase of any error in your code the include() generates the warning but script execution never stopped but when we use require() then incase of any error in your code, it generates a fatal error and execution of the program is stopped.

0 comments: