评论在评论中:
// When you create functions do not assume that variables
// will just magically be available inside it. If you need
// to use some variable inside a function then define them
// as arguments.
function price($price, $vat) {
// Never use a variable or array index without
// first making sure that it exists! You will
// get error messages if they do not exist.
if ( ! isset($_SESSION['vat'])) {
trigger_error('The session variable "vat" is not set');
}
// Since you use 'ex' and 'inc' to figure out if the
// VAT is included or not, what happens it the value
// is neither of those? Maybe $_SESSION['vat'] should be
// a boolean value instead? (I.e. true or false, as
// opposed to one of N values.)
$vatInfo = 'VAT may or may not be included...';
// VAT excluded
if ($_SESSION['vat'] === 'ex') {
$vatInfo = 'Ex. VAT';
}
// VAT included
elseif ($_SESSION['vat'] === 'inc') {
$vatInfo = 'Inc. VAT';
// The value of the $price variable will not be changed
// after this so we can just overwrite it here.
$price = ($price * (1 + $vat / 100));
}
// When it comes to money it is nice to format it so
// that it looks good to the user. number_format() was
// made for this.
$price = number_format($price, 2);
// And *return* it, as opposed to echo'ing it.
return "£{$price} {$vatInfo}";
}
// Pass in the price and VAT rate as arguments so that
// they can be used inside the function.
$price = price($row_products['price'], $VATrate);
$main_description = str_replace('[price]', $price, $row_products['description']);