how to add global functions?
Moderator: General Moderators
how to add global functions?
i have about 5 functions that are repeating on lots of pages. How can I make a global function so I don't need to keep copying the code on each page?
-
cpetercarter
- Forum Contributor
- Posts: 474
- Joined: Sat Jul 25, 2009 2:00 am
Re: how to add global functions?
A common pattern is to place functions in a separate script, say "functions.php" and then to "require" functions.php as part of the initialisation process. Like this:
All the functions in functions.php will then be available to any of the scripts which are called after functions.php has been included.
Code: Select all
require ("functions.php");
// do other things like opening a connection to the database
// then a method of deciding which scripts you want to run, and what page to display
Re: how to add global functions?
ok thankyou. how does this differ from include?
Re: how to add global functions?
php.net:
require() is identical to include() except upon failure it will also produce a fatal E_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.
-
cpetercarter
- Forum Contributor
- Posts: 474
- Joined: Sat Jul 25, 2009 2:00 am
Re: how to add global functions?
Basically, use include() where it isn't fatal if the file to be included is not found. Use require() where there is no point in continuing the script if the file cannot be found.