PHP: Writing your own functions

December 16, 2011

“All custom functions should start with xxx_ so that the developer knows a native PHP function is not being called.*
where xxx == your initials, or the project’s initials, or …”

An example custom function style:

function pwb_my_function($parameter1, $parameter2)
{
global $an_outside_variable;
....
return true;
}

functions with optional parameters

suppose you are using a function with 1 param, and in some new cases, now,
you would like to have a 2nd param. give the second a default value and
you can now pass either 1 or 2 params and be fine.

a 3 param. example:

function example1($param1=0, $param2=NULL, param3='x')
{
if ($param1 != 0) ...
if ($param2) ...
...
}

In this example, all the parameters are optional but, if only 1 param. is passed, it is only accepted as param1. If 2 params are passed, they are param1 and param2, otherwise, all must be passed.

persistent variables in functions

When you want a local variable to persist between instances of a given function, you use the static keyword. Then, each time the function is called, the variable will still have the value it contained from the last time the function was called. … But, not across sessions.

STATIC $variable ;

Leave a Reply

We try to post all comments within 1 business day