请参阅下面的代码,我试图在str_replace中放入一个包含if语句的函数,但是,它没有将它注入脚本中,请提前感谢您的帮助。基本上我需要用if语句替换字符串中的[price]。
function price(){
if ($_SESSION['vat'] == "ex"){
echo('£'.$row_products['price'].'Ex. VAT');
} ?>
<?php if ($_SESSION['vat'] == "inc"){
$total_price = $row_products['price'] *= (1 + $VATrate / 100);
echo('£');
printf("%.2f", $total_price);
echo('Inc. VAT');
}
}
$main_description = str_replace('[price]', price(), $row_products['description']);
答案 0 :(得分:1)
没有经过测试,但有些事情可以解决这个问题:
function price() {
if ($_SESSION['vat'] == "ex"){
return '£'.$row_products['price'].'Ex. VAT';
}
if ($_SESSION['vat'] == "inc"){
$total_price = $row_products['price'] *= (1 + $VATrate / 100);
return sprintf("%s %.2f %s", "£", $total_price, 'Inc. VAT');
}
}
答案 1 :(得分:0)
您无法在需要返回值的函数内回显结果。你的功能应该是这样的:
function price() {
$result = ''
if ($_SESSION['vat'] == "ex"){
$result .= '£'.$row_products['price'].'Ex. VAT' . "\n"
}
if ($_SESSION['vat'] == "inc") {
$total_price = $row_products['price'] *= (1 + $VATrate / 100);
$result .= '£';
$result .= sprintf("%.2f", $total_price);
$result .= 'Inc. VAT';
}
return $result;
}
您将字符串连接起来然后在最后返回它。
答案 2 :(得分:0)
评论在评论中:
// 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']);