如何阅读函数的定义(函数原型)

文档中的每个函数都只是快速参考,学会如何阅读和理解文档将使得 PHP 的使用更加简单。和依赖赖于复制/粘贴范例比起来,用户一定更希望知道如何阅读函数的定义(函数原型):

先决条件,对变量类型的基本理解: 尽管 PHP 是亚类型语言,但对变量类型有一个基本的理解也是非常重要的,因为它们有重要的意义。

函数定义告诉我们函数返回什么类型的值,让我们用函数 strlen() 的定义作为第一个范例:

strlen

(PHP 3, PHP 4, PHP 5)
strlen -- 获取字符串长度

描述
int strlen ( string str )

返回字符串的长度。

表格 Q-1. 函数定义

组成部分说明
strlen 函数名称
(PHP 3, PHP 4, PHP 5) strlen() 在 PHP 3 、PHP 4 和 PHP 5 中都存在
int 该函数返回的值的类型,这里为整型。(例如,字符串的长度是以数字来衡量的)
( string str ) 第一个(本例中是唯一的)参数,在该函数中名为 str,且类型为 string

可以将以上函数的定义写成一般形式:

返回类型    函数名    ( 参数类型   参数名 )

很多函数都有多个变量,例如 in_array()。其函数原型如下:

bool in_array ( mixed needle, array haystack [, bool strict])

这是什么意思?in_array() 返回一个“布尔”值,成功(如果在参数 haystack 中能找到参数 needle)则返回 TRUE 或者失败(如果在参数 haystack 中找不到参数 needle)则返回 FALSE。第一个参数被命名为 needle 且其类型不定,因此我们将其称为“混和”类型。该混和类型的 needle 参数(我们要找的对象)可以适一个标量的值(字符串、整数、或者浮点数),或者一个数组haystack(我们寻找的范围)是第二个参数。第三个可选参数被命名为 strict。所有的可选参数都用 [ 方括号 ] 括起来。手册表明 strict 参数默认值为布尔值 FALSE。需要了解函数工作的细节,请参阅手册中和该函数相关的页面。

有的函数包含更复杂的 PHP 版本信息。我们拿 html_entity_decode() 举例:

(PHP 4 >= 4.3.0, PHP 5)

它意味着该函数不可在 PHP 3 中使用,只可在 PHP 4.3.0 及以后发布的版本中使用。


add a note add a note User Contributed Notes
php dot devel at homelinkcs dot com
13-Jul-2005 08:50
More specifically, an ampersand (&) prepended to an argument name means that the argument will be passed by reference (http://www.php.net/manual/en/language.references.pass.php).
ceo at l-i-e dot com
10-Mar-2005 07:16
Another thing to watch for is the & in the argument list.

That generally means that the function is going to *CHANGE* the value you pass in, in some way, and you can't rely on it being the same as what you handed off to the function.