PHP学习笔记 09 - 函数

PHP 函数

  • 语法:
function functionName($param1, $param2, ...) {
    // do something
}
  • 以关键字 function 开头
  • 函数名字大小写不敏感
  • 参数可以有默认值

示例

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <title>Function</title>
</head>

<body>
    <div class="well">
    <?php

    function greet($greetings = 'Hello world!', $count = 1) {
        for ($i = 0; $i < $count; ++$i) {
            echo "$greetings<br>";
        }
    }

    greet();
    greet('Hi, there!');
    greet('PHP is good!', 3);
    ?>
    </div>
</body>

</html>

查看运行结果

传递引用参数

  • 在参数前加 & 表示传递引用
  • 传递引用可以通过改变形参的值来改变实参

示例

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <title>Pass By Reference</title>
</head>

<body>
    <div class="well">
    <?php

    function passByValue($x) {
        ++$x;
    }

    echo "<h2>Pass By Value</h2>";
    $x = 5;
    echo "origin x: $x<br>";
    passByValue($x);
    echo "after call passByValue(), x: $x<br>"; 

    function passByReference(&$x) {
        ++$x;
    }

    echo "<h2>Pass By Reference</h2>";
    $x = 5;
    echo "origin x: $x<br>";
    passByReference($x);
    echo "after call passByReference(), x: $x<br>";

    ?>
    </div>
</body>

</html>

查看运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值