A function can be defined by the following syntax:
Example #1 Pseudo-code for demonstrating function use
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.\n";
return $retval;
}
?>
Any valid PHP code is likely to appear inside the function or even include other functions and class definitions.
The function name is the same as the other identifier naming rules in PHP. Valid function names begin with a letter or underscore, followed by letters, numbers, or underscores. The regular expression can be expressed as:[a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]*.
Tip
The function does not need to be defined before the call unless the function is conditionally defined in the following two examples.
When a function is conditionally defined, it must be defined before the function is called.
Example #2 Conditional functions
$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";
}
?>
Functions in the Example #3 function
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.\n";
}
}
/* 现在还不能调用bar()函数,因为它还不存在 */
foo();
/* 现在可以调用bar()函数了,因为foo()函数
的执行使得bar()函数变为已定义的函数 */
bar();
?>
All functions and classes in PHP have global scope, can be defined within a function and are called outside, and vice versa.
PHP does not support function overloading, and it is not possible to cancel the definition or redefine a declared function.
Note: The function name is case-insensitive, but it is a good practice to use the same form as it was defined when calling a function.
Recursive functions can be called in PHP.
Example #4 Recursive functions
function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
?>
Note: However, to avoid recursive function/method calls over 100-200 layers, because the stack may crash and the current script terminates. Infinite recursion can be considered a programming error.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The above describes the PHP custom function official document, including the aspects of the content, I hope to be interested in PHP tutorial friends helpful.