This topic is locked

TIP: Custom Function inside events

12/29/2010 11:35:36 AM
PHPRunner Tips and Tricks
F
FunkDaddy author

Ran into a simple problem, thought I'd share the solution here:
Say you want to create a custom function so you can call it several times inside an event in one of your forms. Assume this function must make use of the $values["fieldname"] variable and also data returned via a typical query such as:



global $conn;

$str = "SELECT * FROM products_tbl WHERE ProductID = ".$values["ProductID"];

$rs = db_query($str,$conn);

$data = db_fetch_array($rs);


When writing a function that uses $values and/or $data variables you must make sure they are declared as part of your custom function's argument, otherwise they lose scope inside that function and will generate a PHP error. Thus, when writing a custom function that needs to use those variable write as follows:



function getCommissions(&$values,$data) {
if($values["Whateverfield"] == 1) {

//do something, etc...;

}

};



P.S. Notice the ampersand character in front of the actual $values when we define/create the function...use it here, but not when calling it!
Then when you need to call the new custom function simply call it in the events by writing: getCommissions($values,$data);
Cheers,