简明现代魔法 -> PHP服务器脚本 -> PHP按值传递参数
PHP按值传递参数
2009-09-12
计算含税商品价格
创建一个函数,它接受两个参数,商品原始价格$price和税率$tax,然后计算出商品的含税价格$total。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="css/formStyle.css">
</head>
<script language="javascript">
function chkinput(form)
{
if(form.price.value=="")
{
alert("请输入商品价格");
form.price.select();
return(false);
}
if(form.tax.value=="")
{
alert("请输入商品税");
form.tax.select();
return(false);
}
return(true);
}
</script>
<body>
<table width="600" border="0" align="center" style="font-family:Verdana,宋体;font-size: 12px;">
<form action="<? echo $PHP_SELF; ?>" method="post" onsubmit="return chkinput(this)">
<tr>
<td width="160" height="25" align="right">价格(不含税):</td>
<td width="400"> <input type="text" name="price" size="40" maxlength="80" value="" class="inputcss" />
<span class="STYLE1"></span></td>
</tr>
<tr>
<td height="25" align="right">商品税:</td>
<td> <input type="text" name="tax" size="40" maxlength="80" value="" class="inputcss" />
<span class="STYLE1"> </span></td>
</tr>
<tr>
<td height="25"> </td>
<td> <span class="STYLE1"> </span></td>
</tr>
<?php
$price = $_POST['price'];
$tax = $_POST['tax'];
$total = salestax($price, $tax);
function salestax($price, $tax){
$total = $price + ($price * $tax);
return $total;
}
?>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="提交" class="buttoncss" /> <input type="reset" value="重置" class="buttoncss"></td>
</tr>
<tr>
<td height="25" align="right"> 商品总价(含税):</td>
<td> <input type="text" name="total" size="40" maxlength="80" value="<?php echo $total; ?>" class="inputcss" />
<span class="STYLE1"> </span></td>
</tr>
</form>
</table>
</body>
</html>
先从表单里获取$price和$tax这两个参数,然后通过函数salestax()计算出总价并返回这个总价。创建一个变量$total来接受调用函数之后返回的值,然后将这个变量输出。
程序运行演示
按值传递 passing by value
向函数传递数值或者变量,称为 按值传递 或者 传值。在函数范围内对这些值的任何改变在函数外部都会被忽略。之前我们讨论过了,函数的参数是保存在栈里,速度很快。函数参数进入函数之后会怎么处理,我们可以不用去想,我们只需要处理后返回的结果。
<?php echo "您输入的价格是".$price; echo "您输入的价格是
"; echo "您输入的税率是".$tax; ?>
您输入的税率是
两个变量$price和$tax并没有改变。

