recyclable 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
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

recyclable functions

Post by malcolmboston »

ok, im planning on using functions from now on but i have one question

ok here goes.... this is completely made up and i have no use for it

say i have this
$var + 13 + 6 = $answer;
$answer / $var = $finalanswer

say i created that as a function but then..........

i needed to changed it to
$var + 13333 + 6 = $answer;
$answer / $var = $finalanswer

would i have to create a whole new function or could i do something to the old one?

Cheers,

an intrigued coder
User avatar
vigge89
Forum Regular
Posts: 875
Joined: Wed Jul 30, 2003 3:29 am
Location: Sweden

Post by vigge89 »

Code: Select all

<?php
function some_math ($first, $second = 13) { // if you don't set $second as something (some_math (1)), it would automaticly be set as 13.

$answer = $first + $second + 6;
$final_answer = $answer / $var;

return $final_answer;

}
?>
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

Post by malcolmboston »

hmmm ok thats kool

would i use the same principles in a 'non-integer' line such as a database query?
eletrium
Forum Commoner
Posts: 34
Joined: Tue Feb 10, 2004 3:38 pm

Post by eletrium »

yes
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

vigge89 wrote:

Code: Select all

<?php
function some_math ($first, $second = 13) { // if you don't set $second as something (some_math (1)), it would automaticly be set as 13.

$answer = $first + $second + 6;
$final_answer = $answer / $var;

return $final_answer;

}
?>
Or:

Code: Select all

function calculation_1($a, $b, $c, $d)
{
    return ($a + $b + $c) / $d;
}
Setting arg defaults can be useful. Another thing to look at is defining some constants in a config.php file. A config file creates a single easy to find source to edit sitewide constants. It depends on the particular case whether constants are the best choice. Tax rates would make good constants for example. When they change it's possibly easier to edit a config.php file rather than hunt down all the fns which store tax rate values.

Code: Select all

// add value added tax to the pre vat price
function getTotalPrice($price_ex_vat)
{
    return $price_ex_vat * (1 + VAT_RATE);
}
Post Reply