zoukankan      html  css  js  c++  java
  • 跟着百度学PHP[5]函数篇1-参数

    ps:俺的文章俺懂就行。大家不要拿来学习不然每个人的学习思路不一样。看视屏文章的老师不同笔记不同加上我也是新手上路,还怕误导!请大家看行且思考,帮忙挖Bug也可以。

    案例要求:你可以写一个两行三列的表格吗?N行N列呢?


    我们先来使用php写一个简单的两行三列的表格。(PS:由此引出函数参数的作用)

    <?php 
    /*
    *在写的时候建议是成对的写。
    *比如:
        for ($i=1; $i <=2; $i++) 
        { 
            $table.="<tr>";     //写完立马写另外一个。以免漏泄或者其他未知的意外。
            $table.="</tr>";    //点代表承接。
        }
    *
    * 
     */
    $table = "<table border='1' cellpading='2'>";
        for ($i=1; $i <=2 ; $i++) { 
            $table .= "<tr>";
                for ($j=1; $j <=3 ; $j++) { 
                    $table .= "<td>test</td>";
                }
            $table .= "</tr>";
        }
    $table .="</table>";
    echo $table;
     ?>
    输出效果如下所示:
    test test test
    test test test

    然后我们自定义一个函数,然后将$table放到里面去。

    <?php 
    function createtable(){
        $table = "<table border='1' cellpading='2'>";
            for ($i=1; $i <=2 ; $i++) { 
                $table .= "<tr>";
                    for ($j=1; $j <=3 ; $j++) { 
                        $table .= "<td>test</td>";
                    }
                $table .= "</tr>";
            }
        $table .="</table>";
        echo $table;
    }
     ?>

    这样肯定是不行的。那么我们来研究一下如何将这个表格设置成函数。这时候就是参数出场的时候了。

    方法:function test($x,$y);

    $x和$y就是参数,可有可无,可无限制。

    <?php 
    function createtable($x,$y){
        $table = "<table border='1' cellpading='2'>";
            for ($i=1; $i <=$x ; $i++) {  #将此处本来的2改为了$x,就会自动调用函数里的。
                $table .= "<tr>";
                    for ($j=1; $j <=$y ; $j++) { #将此处本来的3改为了$y
                        $table .= "<td>test</td>";
                    }
                $table .= "</tr>";
            }
        $table .="</table>";
        echo $table;
    }
    createtable(2,3); #调用函数,记住哦,两个参数就要有两个值。否则会出错呢!
     ?>

    可选参数


    前面我们说到的是参数是必须要选择的。那么有没有不必麻烦去选择的自动默认的就有的呢?

    <?php 
    function createtable($x,$y,$color='red'){
        $table = "<table bgcolor=$color border='1'>";
            for ($i=1; $i <=$x ; $i++) { 
                $table .= "<tr>";
                    for ($j=1; $j <= $y ; $j++) { 
                        $table .="<td>Hello World</td>";
                    }
                $table .= "</tr>";
            }
        $table .="</table>";
        echo $table;
    }
    createtable(2,2);
     ?>
  • 相关阅读:
    洛谷P1258小车问题
    洛谷P1028 数的计算
    P1980 计数问题
    洛谷P1907口算练习题
    2018icpc沈阳-K.Let the Flames Begin (约瑟夫环问题)
    Codeforces Round #585 (Div. 2) B. The Number of Products
    字符串部分模板总结
    CF-1209D Cow and Snacks (并查集,图)
    Codeforces Round #584 (div.1+div.2)(补题)
    HDU
  • 原文地址:https://www.cnblogs.com/xishaonian/p/6224038.html
Copyright © 2011-2022 走看看