PHP学习之三:函数

1 创建函数

函数的创建语法如下:

function func($arg_1,$arg_2,...,$arg_n)

{

    ...

}

任何有效的PHP代码都可以在函数中,包含其他函数或类的定义。

在PHP中,调用函数时不需要先声明。对于定义在函数中的函数,只有外层函数调用之后,才能调用内层函数。

<?php
function foo() 
{
  function bar() 
  {
    echo "I don't exist until foo() is called.\n";
  }
}

/* We can't call bar() yet
   since it doesn't exist. */

foo();

/* Now we can call bar(),
   foo()'s processing has
   made it accessible. */

bar();

?>


2 函数参数

PHP在传递参数时,支持按值传递(默认)、按引用传递。此外还支持默认参数与变长参数。

在按引用传递与默认参数时,其形式与C++一样,如下代码所示。

<?php

/* passing by reference */
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}

/* passing default argument */
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
?>

需要注意的是,在传递默认参数时,必须是常量表达式,不能是变量、类成员函数或函数。此外,若有多个参数需要传递,默认参数必须位于非默认参数的右端。

在使用变长参数列表时,需要借助于func_get_args() func_get_arg() , func_arg_num();

<?php
// using varargs function
function pick($a) {
    $argc = func_num_args();
    for ($i = 0; $i < $argc; $i++) {
        $arg = func_get_arg($i);
        if (! is_null($arg)) {
            return $arg;
        }
    }

    return null;
}
?>

3 函数返回值

函数可以返回任何类型的值,若无return语句,则返回NULL。


4 函数变量

PHP支持以字符串的方式调用一个函数。下面的函数从一个类中执行这个操作。

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }
    
    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

5 匿名函数

也称为闭包。下面是一个使用了use引入外部参数的匿名函数。

<?php
function getTotal($tax,$products)
{
        $total = 0.00;
        
        $func =
            function ($quantity, $product) use ($tax, &$total)
            {
                $pricePerItem = strtoupper($product));
                $total += ($pricePerItem * $quantity) * ($tax + 1.0);
            };
        
        func(products);
        return round($total, 2);
    
}
?>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值