Page 1 of 1

how to add global functions?

Posted: Wed Apr 14, 2010 10:22 am
by wurdup
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?

Re: how to add global functions?

Posted: Wed Apr 14, 2010 10:30 am
by cpetercarter
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:

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
All the functions in functions.php will then be available to any of the scripts which are called after functions.php has been included.

Re: how to add global functions?

Posted: Wed Apr 14, 2010 10:51 am
by wurdup
ok thankyou. how does this differ from include?

Re: how to add global functions?

Posted: Wed Apr 14, 2010 11:58 am
by solid
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.

Re: how to add global functions?

Posted: Wed Apr 14, 2010 2:51 pm
by cpetercarter
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.