• php函数


    在 PHP 3 中,函数必须在被调用之前定义。而 PHP 4 则不再有这样的 条件。除非函数如以下两个范例中有条件的定义。

    有条件的函数:

    <?php
    $makefoo 
    true;
    /* We can't call foo() from here
       since it doesn't exist yet,
       but we can call bar() */

    bar();

    if (
    $makefoo) {
      function 
    foo ()
      {
        echo 
    "I don't exist until program execution reaches me. ";
      }
    }

    /* Now we can safely call foo()
       since $makefoo evaluated to true */

    if ($makefoofoo();

    function 
    bar()
    {
      echo 
    "I exist immediately upon program start. ";
    }

    ?>

    函数中的函数:

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

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

    foo();

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

    bar();

    ?>

    函数的参数:php支持按值传递参数(默认)、通过引用传递、默认参数值。向函数传递数组:缺省情况下函数参数通过值传递

    <?php
    function takes_array($input)
    {
        echo 
    "$input[0] + $input[1] = "$input[0]+$input[1];
    }
    ?>

    引用传递函数参数:默认值通常是常量表达式,不是变量,类成员,或者函数调用

    <?php
    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.'
    ?>

    默认参数的值

    <?php
    function takes_array($input)
    {
        echo 
    "$input[0] + $input[1] = "$input[0]+$input[1];
    }
    ?>

    输出结果:

    Making a cup of cappuccino.
    Making a cup of espresso

    请注意当使用默认参数时,任何默认参数必须放在任何非默认参数的右侧;否则, 可能函数将不会按照预期的情况工作。考虑下面的代码片断
    <?php
    function makeyogurt ($flavour$type "acidophilus")
    {
        return 
    "Making a bowl of $type $flavour. ";
    }

    echo 
    makeyogurt ("raspberry");   // works as expected
    ?>

    函数返回值:返回一个引用,必须在函数声明和指派返回值给一个变量时都使用引用操作符 & 
    <?php
    function &returns_reference()
    {
        return 
    $someref;
    }

    $newref =& returns_reference();
    ?>

     

  • 相关阅读:
    博客开篇--别让自己在临终前后悔
    预言帖,WP7迟早有一天会失败
    sql server 列值转列名的问题
    “《面对面做好每一天》中国短道速滑教练李琰”读后感
    原型要做到什么程度
    不得不承认我的高度不够,通过项目提升了.
    项目进度很慢
    原型确认后准备开发(1)
    邮件发送打印机更改打印机连接的通知
    onclick事件中加href
  • 原文地址:https://www.cnblogs.com/lindsayzhao103011/p/3361712.html
Copyright © 2020-2023  润新知