A Guide to Writing Functions

A Guide to Writing Functions

If you find yourself writing the same few lines of code more than twice, convert those lines into a PHP function. In order to minimize the amount of code for websites and web applications, call functions within functions. The most effective functions are ones that are reusable.

Naming Functions

The names you choose for your functions should provide a good hint about what the function does. However, you don’t want your function name to be too long or too specific in case you want to modify it later.

For example, suppose you have a function called getHomePhoneNumber($clientID) that retrieves and returns a home phone number of a specific client stored in a database. Later, you want to retrieve the client’s cell phone number. You would either have to write another function, identical to getHomePhoneNumber($clientID); or you would have to change the name of the existing function to getPhoneNumber($clientID) and edit all calls to that function; or leave the name as getHomePhoneNumber($clientID), which could lead to confusion. Prudently choosing the function name when you write it maximizes efficiency.

Additionally, when creating a plugin for WordPress, it is wise to use prefixes that indicate plugin package. For example, if you create a plugin called ‘Banner Editor’, you should prefix all functions with ‘be_’. This naming practice prevents important functions in other plugin packages from being overwritten.

Choosing Function Arguments

Use arguments for your functions. However, using too many arguments could get messy and unmanageable. If you find yourself using more than three arguments in a function, it it probably a good idea to split that function up into smaller functions.

PHP allows you to set default argument values in your functions. The benefit of default argument values is that it allows you to call the function multiple times without having to set default values each time. It also allows you to leave arguments blank when the function is called, which results in clean and concise coding. Default argument values are always overwritten if you assign values to the arguments when you call the function.

By: Sarah

The comments are closed.

No reviews yet