PHP 之函数

一、函数定义

function  foo ( $arg_1 ,  $arg_2 ,  /* ..., */  $arg_n )
{
    echo  "Example function.\n" ;
    return  $retval ;
}

二、函数参数

通过参数列表可以传递信息到函数,即以逗号作为分隔符的表达式列表。参数是从左向右求值的。

PHP 支持按值传递参数(默认),通过引用传递参数以及默认参数。也支持可变长度参数列表。 

1、引用传递

function  add_some_extra (& $string )
{
     $string  .=  'and something extra.' ;
}
$str  =  'This is a string, ' ;
add_some_extra ( $str );
echo  $str ;     // outputs 'This is a string, and something extra.'  

2、默认传递

function  takes_array ( $input )
{
    echo  " $input [ 0 ]  +  $input [ 1 ]  = " ,  $input [ 0 ]+ $input [ 1 ];
}

3、可变长度参数

function  sum (... $numbers ) {
    $acc  =  0 ;
    foreach ( $numbers  as  $n ) {
         $acc  +=  $n ;
    }
    return  $acc ;
}

echo  sum ( 1 ,  2 ,  3 ,  4 ); 

三、返回值

值通过使用可选的返回语句返回。可以返回包括数组和对象的任意类型。返回语句会立即中止函数的运行,并且将控制权交回调用该函数的代码行。

function  square ( $num )
{
    return  $num  *  $num ;
}
echo  square ( 4 );    // outputs '16'.

四、可变函数

PHP 支持可变函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且尝试执行它。可变函数可以用来实现包括回调函数,函数表在内的一些用途。

可变函数不能用于例如 echo print unset() isset() empty() include require 以及类似的语言结构。需要使用自己的包装函数来将这些结构用作可变函数。 

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()

五、内置函数

PHP 有很多标准的函数和结构。还有一些函数需要和特定地 PHP 扩展模块一起编译,否则在使用它们的时候就会得到一个致命的“未定义函数”错误。例如,要使用 image 函数中的 imagecreatetruecolor() ,需要在编译 PHP 的时候加上 GD 的支持。或者,要使用 mysql_connect() 函数,就需要在编译 PHP 的时候加上 MySQL 支持。有很多核心函数已包含在每个版本的 PHP 中如字符串变量函数。调用 phpinfo() 或者 get_loaded_extensions() 可以得知 PHP 加载了那些扩展库。

六、匿名函数

匿名函数,也叫闭包函数,允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。当然,也有其它应用的情况。

$message  =  'hello' ;

 // 没有 "use"
 $example  = function () {
     var_dump ( $message );
};
echo  $example ();

 // 继承 $message
 $example  = function () use ( $message ) {
     var_dump ( $message );
};
echo  $example ();

 // Inherited variable's value is from when the function
// is defined, not when called
 $message  =  'world' ;
echo  $example ();

 // Reset message
 $message  =  'hello' ;

 // Inherit by-reference
 $example  = function () use (& $message ) {
     var_dump ( $message );
};
echo  $example ();

 // The changed value in the parent scope
// is reflected inside the function call
 $message  =  'world' ;
echo  $example ();

 // Closures can also accept regular arguments
 $example  = function ( $arg ) use ( $message ) {
     var_dump ( $arg  .  ' '  .  $message );
};
 $example ( "hello" );
Notice: Undefined variable: message in /example.php on line 6
NULL
string(5) "hello"
string(5) "hello"
string(5) "hello"
string(5) "world"
string(11) "hello world"
posted @ 2019-12-12 15:30  样子2018  阅读(142)  评论(0)    收藏  举报