函数
在线手册:中文 英文
PHP手册

用户自定义函数

一个函数可由以下的语法来定义:

Example #1 展示函数用途的伪代码

<?php
function foo($arg_1$arg_2, ..., $arg_n)
{
    echo 
"Example function.\n";
    return 
$retval;
}
?>

任何有效的 PHP 代码都有可能出现在函数内部,甚至包括其它函数和定义。

函数名和 PHP 中的其它标识符命名规则相同。有效的函数名以字母或下划线打头,后面跟字母,数字或下划线。可以用正则表达式表示为:[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Tip

请参见Userland Naming Guide

除非是下面两个例子中的情况,函数必须在其调用之前定义。

Example #2 条件函数(Conditional functions)

<?php

$makefoo 
true;

/* 我们不能在处调用foo()函数,
   因为它还不存在,但可以调用bar()函数。*/

bar();

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

/* 现在我们可以安全调用函数 foo()了,
   因为 $makefoo 值为真 */

if ($makefoofoo();

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

?>

Example #3 函数中的函数

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

/* 现在还不能调用bar()函数,因为它还不存在 */

foo();

/* 现在可以调用bar()函数了,因为foo()函数
   的执行使得bar()函数变为已定义的函数 */

bar();

?>

PHP 中的所有函数和类都具有全局作用域,可以在内部定义外部调用,反之亦然。

PHP 不支持函数重载,也不可能取消定义或者重定义已声明的函数。

Note: 函数名是大小写无关的,不过在调用函数的时候,通常使用其在定义时相同的形式。

PHP 支持可变数量的参数默认参数。具体请参考: func_num_args()func_get_arg(),以及func_get_args()

在 PHP 中可以调用递归函数。但是要避免递归函数/方法调用超过 100-200 层,因为可能会破坏堆栈从而使当前脚本终止。

Example #4 递归函数

<?php
function recursion($a)
{
    if (
$a 20) {
        echo 
"$a\n";
        
recursion($a 1);
    }
}
?>


函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 用户自定义函数

用户评论:

Caleb1994 (02-Apr-2012 07:11)

There isn't anything wrong with that. B() is in the global scope, and is therefore accessible at any point in the script. You may have been thinking of something like example #2, but in that example, foo() was encased within another block, which means it wasn't parsed until it's condition was checked and met.

I guess you could think of it as a recursive parser (Although I cannot claim to have any idea of how PHP's parser was coded on the backend). The top-level code (not in any brackets, functions, or other types of blocks) is parsed first. All coorasponding functions are defined, and stored. Next, the script begins to execute. When a conditional, block, or function is met, the block is scanned and any new functions, which need defining, are defined at that time.

I know that statement was two years old, but I figured I'd post some sort of explanation in order to clear up any other misguided new users. I hate finding a post with the exact same question, and no answer on the internet.

XKCD, Wisdom of the Ancients: http://xkcd.com/979/

gestioni at gerry dot it (12-Nov-2010 06:43)

<?php

function A(){
    echo(
"Hello, I'm A\n");

}
echo(
"I just defined A\n");
return;

function
B(){
    echo(
"Hello, I'm B\n");

}
echo(
"I just defined B\n");
?>

If you include this file, the second echo() is not excuted but B() is still defined