Jump to content

Recommended Posts

Posted

Functions:

include('/filepath/filename')


require('/filepath/filename')


include_once('/filepath/filename')


require_once('/filepath/filename')
include() and include_once() will merely generate a warning on failure, while require() and require_once() will cause a fatal error and termination of the script. include_once() and require_once() differ from simple include() and require() in that they will allow a file to be included only once per PHP script. Let's see an example:

//

<?php

//we have the: include_me.php

echo 'I\ 've been included!<br />';

?>

Every time this script is included it will display the message "I've been included!", so we know it's worked. Now, let's test the various ways we can include this file in another script:

<?php

//This works fine

echo '<br />Requiring once: ';

require_once 'include_me.php';

//This works fine as well

echo '<br />Including: ';

include 'include_me.php';

//Nothing happens as file is already included

echo '<br />Includind once: ';

include_once 'include_me.php';

//This is fine

echo '<br />Requiring: ';

require 'include_me.php';

//Again nothing happens - the file is included

echo '<br />Requiring once again: ';

require-once 'include_me.php';

//Produces a warinig message as the file doesn't exist

echo '<br />Include the wrong file: ';

include 'include_wrong.php';

//Produces a fatal error and script execution halts

echo '<br />Requiring the wrong file: ';

require 'include_wrong.php';

//This will never be executed as we have a fatal error

echo '<br />Including again: ';

include 'include_me.php';

?>

The result will be sth like this:

Requiring once: I've been included

Including: I've been included

Including once:

Requiring: I've been included

Requiring once:

Include the wrong file:

Warning: Failed opening 'inlcude_wrong.php' for inclusion

Requiring the wrong file: Fatal error: Failed opening required 'include_wrong.php'

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.