函数

来源:互联网 发布:软件架构是什么 编辑:程序博客网 时间:2024/06/06 07:40

用户自定义函数

 一个函数可由以下的语法来定义:Example #1 展示函数用途的伪代码<?phpfunction foo($arg_1, $arg_2, /* ..., */ $arg_n){    echo "Example function.\n";    return $retval;}?> 当一个函数是有条件被定义时,必须在调用函数之前定义。Example #2 有条件的函数<?php$makefoo = true;/* 不能在此处调用foo()函数,   因为它还不存在,但可以调用bar()函数。*/bar();if ($makefoo) {  function foo()  {    echo "I don't exist until program execution reaches me.\n";  }}/* 现在可以安全调用函数 foo()了,   因为 $makefoo 值为真 */if ($makefoo) foo();function bar(){  echo "I exist immediately upon program start.\n";}?>Example #3 函数中的函数<?phpfunction foo(){  function bar()  {    echo "I don't exist until foo() is called.\n";  }}/* 现在还不能调用bar()函数,因为它还不存在 */foo();/* 现在可以调用bar()函数了,因为foo()函数   的执行使得bar()函数变为已定义的函数 */bar();?>

注:PHP不支持函数重载,也不可能取消定义或者重定义已声明的函数
注:函数名是大小写无关的,不过在调用函数的时候,使用其定义时相同的形式是个好习惯。

PHP可变数量的参数列表

PHP在用户自定义函数中支持可变数量的参数列表。
在PHP5.6及以上的版本中,由…语法实现;在PHP5.5及更早版本中,使用函数func_num_args(),func_get_arg(),和func_get_args()实现

<?php    function sum(...$number) {        $acc = 0;        foreach ($numbers as $n){            $acc += $n;        }        return $acc;    }    echo sum(1,2,3,4)

php 函数使用可变数量的参数

返回值
注:如果省略了return,则返回值为NULL。

返回一个引用

 从函数返回一个引用,必须在函数声明和指派返回值给一个变量时都使用引用运算符 &:Example #3 从函数返回一个引用<?php    function &rreturns_reference()    {        return $someref;    }    $newref = & returns_reference();

可变函数:

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

匿名函数:

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

闭包函数也可以作为变量的值来使用。PHP会自动把此种表达式转换成内置类Closure的对象实例。把一个 closure 对象赋值给一个变量的方式与普通变量赋值的语法是一样的,最后也要加上分号:

<?php$greet = function($name){    printf("Hello %s\r\n",$name);}$greet('World');$greet('PHP');

闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去。 PHP 7.1 起,不能传入此类变量: superglobals、 $this 或者和参数重名。

<?php$message = 'hello';// 没有 "use"$example = function () {    var_dump($message);};echo $example();//注意这里通过继承得到的是来自定义时的$message,而非用的在哪调用的// 继承 $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");?>

注意:这些变量都必须在函数或类的头部声明。从父作用域中继承变量与使用全局变量是不同的。
全局变量存在于一个全局的范围,无论当前在执行的是哪个函数。而闭包的父作用域是定义该闭包的函数(不一定是调用它的函数)

Example #4 Closures 和作用域<?php// 一个基本的购物车,包括一些已经添加的商品和每种商品的数量。// 其中有一个方法用来计算购物车中所有商品的总价格,该方法使// 用了一个 closure 作为回调函数。class Cart{    const PRICE_BUTTER  = 1.00;    const PRICE_MILK    = 3.00;    const PRICE_EGGS    = 6.95;    protected   $products = array();    public function add($product, $quantity)    {        $this->products[$product] = $quantity;    }    public function getQuantity($product)    {        return isset($this->products[$product]) ? $this->products[$product] :               FALSE;    }   public function getTotal($tax)    {        $total = 0.00;        $callback =            function ($quantity, $product) use ($tax, &$total)            {                $pricePerItem = constant(__CLASS__ . "::PRICE_" .                    strtoupper($product));                $total += ($pricePerItem * $quantity) * ($tax + 1.0);            };        array_walk($this->products, $callback);        return round($total, 2);;    }}$my_cart = new Cart;// 往购物车里添加条目$my_cart->add('butter', 1);$my_cart->add('milk', 3);$my_cart->add('eggs', 6);// 打出出总价格,其中有 5% 的销售税.print $my_cart->getTotal(0.05) . "\n";// 最后结果是 54.29?>
原创粉丝点击