【PHP学习】函数

1.创建函数

其实PHP里面对于函数的操作跟C语言类似,只是多加了些功能,这里我就写下多出来的了,没写的照搬C语言就行。
从函数返回多个值

利用list()构造可以很方便地从数组中获取值。比如:

<?php
    $colors=array("red","blue","green");
    list($red,$blue,$green)=$colors;
?>

执行了list()构造后,$red$blue$green分别被赋值为red、blue和green。

<?php
    function retrieveUserProfile()
    {
        $user[]="Jason Gilmore";
        $user[]="jason@example.com";
        $user[]="English";
        return $user;
    }

    list($name,$email,$language)=retrieveUserProfile();
echo "Name:$name,email:$email,language:$language";
?>

递归函数

这里可能是书本写的不太全,目前不太明白PHP的递归机制,所以可能会查些资料,作为补充。
这是书本上还贷计算器的代码:

<?php 
    function amortizationTable($pNum,$periodicPayment,$balance,$monthlyInterest)
    {
        $paymentInterest=round($balance*$monthlyInterest,2);
        $paymentPrincipal=round($periodicPayment-$paymentInterest,2);
        $newBalance=round($balance-$paymentPrincipal,2);
        if($newBalance<$paymentPrincipal){
            $newBalance=0;
        }
        printf("<tr><td>%d</td>",$pNum);
        printf("<td>$%s</td>",number_format($newBalance,2));
        printf("<td>$%s</td>",number_format($periodicPayment,2));
        printf("<td>$%s</td>",number_format($paymentPrincipal,2));
        printf("<td>$%s</td></tr>",number_format($paymentInterest,2));
        if($newBalance>0){
            $pNum++;
            amortizationTable($pNum, $periodicPayment, $newBalance, $monthlyInterest);
        }
        else{
            return 0;
        }
    }
    $balance=10000.00;
    $interestRate=.0575;
    $monthlyInterest=$interestRate/12;
    $termLength=5;
    $paymentsPerYear=12;
    $paymenetNumber=1;
    $totalPayments=$termLength+$paymentsPerYear;
    $intCalc=1+$interestRate/$paymentsPerYear;
    $periodicPayment=$balance*pow($intCalc,$totalPayments)*($intCalc-1)/(pow($intCalc,$totalPayments)-1);
    $periodicPayment=round($periodicPayment,2);
    echo "<table width='50%' align='center' border='1'>";
    echo "<tr>
            <th>Payment Number</th><th>Balance</th>
            <th>Payment</th><th>Principal</th><th>Interest</th>
            </tr>";
    amortizationTable($paymenetNumber,$periodicPayment,$balance,$monthlyInterest);
    echo "</table>";
?>

函数库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值