how to add global functions?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wurdup
Forum Commoner
Posts: 39
Joined: Thu Apr 01, 2010 11:36 am

how to add global functions?

Post 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?
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: how to add global functions?

Post 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.
wurdup
Forum Commoner
Posts: 39
Joined: Thu Apr 01, 2010 11:36 am

Re: how to add global functions?

Post by wurdup »

ok thankyou. how does this differ from include?
solid
Forum Commoner
Posts: 28
Joined: Wed Aug 12, 2009 11:56 am

Re: how to add global functions?

Post 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.
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: how to add global functions?

Post 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.
Post Reply