PHP 手册

版权信息

Copyright © 1997 - 2013,PHP 文档组版权所有。发行本资料必须服从 Creative Commons Attribution 3.0 或更新版许可中阐明的条款及条件。Creative Commons Attribution 3.0 license 的副本已随本手册发行。其最新版本位于 » http://creativecommons.org/licenses/by/3.0/

如有兴趣再发行或再版此文档的全部或部分内容,不论修改过与否,或有任何问题,请联系版权所有者 » doc-license@lists.php.net。注意,本地址映射到一个公开归档的邮件列表。

PHP 手册

序言

PHP, 即”PHP: Hypertext Preprocessor”,是一种被广泛应用的开源通用脚本语言,尤其适用于 Web 开发并可嵌入 HTML 中去。 它的语法利用了C、Java 和 Perl,易于学习。该语言的主要目标是允许 Web 开发人员快速编写动态生成的 Web 页面,但 PHP 的用途远不只于此。

本手册主要由函数参考, 但也包含了语言参考,PHP 一些主要产品特点的说明, 及其他补充信息。

可在» http://www.php.net/download-docs.php下载此手册的几种格式。 更多关于如何开发本手册的信息可参阅附录:“关于此手册”。 如果你对PHP 的历史感兴趣,可访问相关附录。

作者与贡献者

在手册的首页上仅突出了目前最活跃的人员,但还有更多的贡献者正在帮助我们工作或在过去给项目提供过巨大的帮助。有许多不知名的人帮助在手册中写下用户评论,并不断地包含在参考中,也很感谢他们的努力。下面所提供的列表均以字母顺序排序。

作者与编辑

下列人员曾经或者目前正在为本手册添砖加瓦: Bill Abt, Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Nilgün Belma Bugüner, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Peter Cowburn, Daniel Egeberg, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Justin Martin, Rafael Martinez, Rick McGuire, Moacir de Oliveira Miranda Júnior, Kalle Sommer Nielsen, Yasuo Ohgaki, Richard Quadling, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Yannick Torres, Michael Wallner, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar 和 Andrei Zmievski.

下列人员对本手册做了相当数量的编辑工作: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe 和 Egon Schmid.

用户评论维护者

目前最活跃的维护者是: Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda 和 Maciek Sokolewicz.

下列人员为维护用户评论作出了巨大的努力: Mehdi Achour, Daniel Beckham, Friedhelm Betz, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, Sean Coates, James Cox, Vincent Gevers, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Etienne Kneuss, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Hannes Magnusson, Maxim Maletsky, Bobby Matthis, James Moore, Philip Olson, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles 和 Jeroen van Wolffelaar.

中文翻译外部支持团队

PHP手册中文翻译工作是一项长期而又艰巨的工作,为了让这个工作得以持久进行下去, 我们组织了 » PHP手册中文翻译补完计划 。 下列人员目前正在参与该计划:codingall.com(赵磊)、cuimuxi(崔玉松)、cztviztor、gaojian1226、 HaoHappy(陈浩)、HonestQiao(乔楚)、kendotom、lgg860911、loosen.copen、miusun01(李鼎峰)、 ping3608、r.anerg(罗翀)、suppersoft(paris.wang)、tor.browser.bridge(王祥中)、 wind.golden(陈金)。

入门指南

简介

PHP 是什么?

PHP(“PHP: Hypertext Preprocessor”,超文本预处理器的字母缩写)是一种被广泛应用的开放源代码的多用途脚本语言,它可嵌入到 HTML中,尤其适合 web 开发。

以上是一个简单的回答,不过这是什么意思呢?请看如下例子:

例 #1 一个介绍性的范例

<html>
   <head>
       <title>Example</title>
   </head>
   <body>
       <?php
       echo "Hi, I'm a PHP script!";
       ?>
   </body>
</html>

请注意这个范例和其它用 C 或 Perl 语言写的脚本之间的区别——与用大量的命令来编写程序以输出 HTML 不同的是,我们用 PHP 编写了一个 HTML 脚本,其中嵌入了一些代码来做一些事情(例如,在本例中输出了一些文本)。PHP 代码被包含在特殊的起始符和结束符中,使得可以进出“PHP 模式”。

和客户端的 JavaScript 不同的是,PHP 代码是运行在服务端的。如果在服务器上建立了如上例类似的代码,则在运行该脚本后,客户端就能接收到其结果,但他们无法得知其背后的代码是如何运作的。甚至可以将 web 服务器设置成让 PHP 来处理所有的 HTML 文件,这么一来,用户就无法得知服务端到底做了什么。

使用 PHP 的一大好处是它对于初学者来说极其简单,同时也给专业的程序员提供了各种高级的特性。当看到 PHP 长长的特性列表时,请不要害怕。可以很快的入门,只需几个小时就可以自己写一些简单的脚本。

尽管 PHP 的开发是以服务端脚本为目的,但事实上其功能远不局限与此。请继续读后面的章节,在“PHP 能做什么”一节中将获得更多的信息。如果对 web 编程感兴趣,也可以阅读简明教程。

PHP 能做什么?

PHP 能做任何事。PHP 主要是用于服务端的脚本程序,因此可以用 PHP 来完成任何其它的 CGI 程序能够完成的工作,例如收集表单数据,生成动态网页,或者发送/接收 Cookies。但 PHP 的功能远不局限于此。

PHP 脚本主要用于以下三个领域:

  • 服务端脚本。这是 PHP 最传统,也是最主要的目标领域。开展这项工作需要具备以下三点:PHP 解析器(CGI 或者服务器模块)、web 服务器和 web 浏览器。需要在运行 web 服务器时,安装并配置 PHP,然后,可以用 web 浏览器来访问 PHP 程序的输出,即浏览服务端的 PHP 页面。如果只是实验 PHP 编程,所有的这些都可以运行在自己家里的电脑中。请查阅安装一章以获取更多信息。
  • 命令行脚本。可以编写一段 PHP 脚本,并且不需要任何服务器或者浏览器来运行它。通过这种方式,仅仅只需要 PHP 解析器来执行。这种用法对于依赖 cron(Unix 或者 Linux 环境)或者 Task Scheduler(Windows 环境)的日常运行的脚本来说是理想的选择。这些脚本也可以用来处理简单的文本。请参阅 PHP 的命令行模式以获取更多信息。
  • 编写桌面应用程序。对于有着图形界面的桌面应用程序来说,PHP 或许不是一种最好的语言,但是如果用户非常精通 PHP,并且希望在客户端应用程序中使用 PHP 的一些高级特性,可以利用 PHP-GTK 来编写这些程序。用这种方法,还可以编写跨平台的应用程序。PHP-GTK 是 PHP 的一个扩展,在通常发布的 PHP 包中并不包含它。如果对 PHP-GTK 感兴趣,请访问其» 网站以获取更多信息。

PHP 能够用在所有的主流操作系统上,包括 Linux、Unix 的各种变种(包括 HP-UX、Solaris 和 OpenBSD)、Microsoft Windows、Mac OS X、RISC OS 等。今天,PHP已经支持了大多数的 web 服务器,包括 Apache、Microsoft Internet Information Server(IIS)、Personal web Server(PWS)、Netscape 以及 iPlant server、Oreilly Website Pro Server、Caudium、Xitami、OmniHTTPd 等。对于大多数的服务器,PHP 提供了一个模块;还有一些 PHP 支持 CGI 标准,使得 PHP 能够作为 CGI 处理器来工作。

综上所述,使用 PHP,可以自由地选择操作系统和 web 服务器。同时,还可以在开发时选择使用面对过程和面对对象,或者两者混和的方式来开发。尽管 PHP 4 不支持 OOP 所有的标准,但很多代码仓库和大型的应用程序(包括 PEAR 库)仅使用 OOP 代码来开发。PHP 5 弥补了 PHP 4 的这一弱点,引入了完全的对象模型。

使用 PHP,并不局限于输出 HTML。PHP 还能被用来动态输出图像、PDF 文件甚至 Flash 动画(使用 libswf 和 Ming)。还能够非常简便的输出文本,例如 XHTML 以及任何其它形式的 XML 文件。PHP 能够自动生成这些文件,在服务端开辟出一块动态内容的缓存,可以直接把它们打印出来,或者将它们存储到文件系统中。

PHP 最强大最显著的特性之一,是它支持很大范围的数据库。用户会发现利用 PHP 编写数据库支持的网页简单得难以置信。目前,PHP 支持如下数据库:

  • Adabas D
  • dBase
  • Empress
  • FilePro(只读)
  • Hyperwave
  • IBM DB2
  • Informix
  • Ingres
  • InterBase
  • FrontBase
  • mSQL
  • Direct MS-SQL
  • MySQL
  • ODBC
  • Oracle(OCI7 和 OCI8)
  • Ovrimos
  • PostgreSQL
  • SQLite
  • Solid
  • Sybase
  • Velocis
  • Unix dbm

同时还有一个叫做 PDO 的数据库抽象扩展库使得可以自由地使用该扩展库支持的任何数据库。另外,PHP 还支持 ODBC,即 Open Database Connection Standard(开放数据库连接标准),因此可以连接任何其它支持该世界标准的数据库。 PHP 还支持利用诸如 LDAP、IMAP、SNMP、NNTP、POP3、HTTP、COM(Windows 环境)等不计其数的协议的服务。还可以开放原始网络端口,使得任何其它的协议能够协同工作。PHP 支持和所有 web 开发语言之间的 WDDX 复杂数据交换。关于相互连接,PHP 已经支持了对 Java 对象的即时连接,并且可以将他们自由的用作 PHP 对象。甚至可以用我们的 CORBA 扩展库来访问远程对象。

PHP 具有极其有效的文本处理特性,支持从 POSIX 扩展或者 Perl 正则表达式到 XML 文档解析。为了解析和访问 XML 文档,PHP 4 支持 SAX 和 DOM 标准,也可以使用 XSLT 扩展库来转换 XML 文档。PHP 5 基于强健的 libxm2 标准化了所有的 XML 扩展,并添加了 SimpleXML 和 XMLReader 支持,扩展了其在 XML 方面的功能。

另外,还有很多其它有趣的扩展库,他们根据字母和 分类归类列出。例如 mnoGoSearch 搜索引擎函数、IRC 网关函数、多种压缩工具(gzip、bz2、zip)、日历转换、翻译……。 还有一些第三方的PECL扩展没有在PHP手册中列出,例如 » XDebug

由于在这里无法列出 PHP 所有的特性和可提供的便利,请参阅安装以及函数参考有关章节以获取关于这里提到的扩展库更多的信息。

简明教程

本章将给出关于 PHP 的简明教程。虽然 PHP 的功能并不局限于生成动态的 web 页面,但本章的内容仅涉及于此。请查阅“PHP 能做什么”一节以获取更多信息。

使用了 PHP 的 web 页面将被和通常的 HTML 页面一样处理,可以用通常建立 HTML 页面的方法来建立和编辑它们。

需要些什么?

在本教程中,假设用户的服务器已经安装并运行了 PHP,所有以 .php 结尾的文件都将由 PHP 来处理。在大部分的服务器上,这是 PHP 的默认扩展名,不过,也请询问服务器管理员以确认。如果服务器支持 PHP,则不需要做任何事情。只用建立 .php 文件,并把它们放置到 web 目录中,服务器将神奇地自动解析这些文件。不用编译任何东西,也不用安装任何其它的工具,仅仅只需把这些使用了 PHP 的文件想象成简单的 HTML 文件,其中只不过多了一种新的标识符,在这里可以做各种各样的事情。大多数的 web 主机都提供 PHP 的支持,如果你的主机不支持,可以访问 » PHP 相关链接来查找支持 PHP 的 web 主机。

假设用户希望在本地机器开发以节约宝贵的带宽。在这种情况下,需要安装一个诸如 » Apache 的 web 服务器,当然还有 » PHP。可能还希望安装一个数据库,例如 » MySQL。

可以一个个的安装它们或选择一个更简单的方法。可以参考本手册中 PHP 安装说明的相关章节(假设已经配置好了某个 web 服务器)。若在自己安装 PHP 时出现了问题,建议在» 安装邮件列表中询问。如果想使用更简便的方法安装 PHP,那么可以考虑» 获取一个预先配置的安装包,用这个安装包,只用点击几下鼠标,就可以自动地安装所有这些系统。在任何操作系统下建立有 PHP 支持的 web 服务器都十分简单,包括 MacOSX、Linux 和 Windiws。在 Linux 下,会发现 » rpmfind 和 » PBone 能够在获取 RPM 时提供帮助。也可以使用 » apt-get 搜索 Debian 的相关软件包。

第一个 PHP 页面

在 web 服务器根目录(DOCUMENT_ROOT)下建立一个文件名为 hello.php,然后完成如下内容:

例 #1 第一个 PHP 脚本:hello.php

<html>
<head>
 <title>PHP 测试</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>

在浏览器的地址栏里输入 web 服务器的 URL 访问这个文件,在结尾加上“/hello.php”。如果本地开发,那么这个 URL 一般是 http://localhost/hello.php 或者 http://127.0.0.1/hello.php,当然这取决于 web 服务器的设置。如果所有的设置都正确,那么这个文件将被 PHP 解析,浏览器中将会输出如下结果:

<html>
<head>
 <title>PHP 测试</title>
</head>
<body>
<p>Hello World</p>
</body>
</html>

该程序非常的简单,它仅仅只是利用了 PHP 的 echo 语句显示了 Hello World。用户一定不会满足与此。请注意该文件无需被执行或以任何方式指定。服务器会找到该文件并提供给 PHP 进行解释,因为使用了“.php”的扩展名,服务器已被配置成自动传递有着“.php”扩展名的文件给 PHP。一个普通的 HTML 文件,加上了几个特别的标签,就可以做很多非常有趣的事情!

如果试过了这个例子,但是没有得到任何输出,或者浏览器弹出了下载框,或者浏览器以文本方式显示了源文件,可能的原因是服务器还没有支持 PHP,或者没有正确配置。需要请服务器的管理员根据本手册“安装”一章的内容使得服务器支持 PHP。如果本地开发,请阅读手册有关安装的章节以确保所有的设置都正确。还要确认通过浏览器访问的 URL 确实指向了服务器上的这个文件。如果只是从本地文件系统调用这个文件,它不会被 PHP 解析。如果问题仍然存在,请通过 » PHP 在线支持中的各种方式获取帮助。

以上例子的目的是为了显示 PHP 特殊标识符的格式。在这个例子中,用 <?php 来表示 PHP 标识符的起始,然后放入 PHP 语句并通过加上一个终止标识符 ?> 来退出 PHP 模式。可以根据自己的需要在 HTML 文件中像这样开启或关闭 PHP 模式。请参阅手册中“PHP 基本语法”以获取更多信息。

注解

关于换行 尽管换行在 HTML 中的实际意义不是很大,但适当地使用换行可以使 HTML 代码易读且美观。PHP 会在输出时自动删除其结束符 ?> 后的一个换行。该功能主要是针对在一个页面中嵌入多段 PHP 代码或者包含了无实质性输出的 PHP 文件而设计,与此同时也造成了一些疑惑。如果在 PHP 结束符 ?> 后输出换行的话,可以在其后加一个空格,或者在最后的一个 echo/print 语句中加入一个换行。

注解

关于文本编辑器 有很多文本编辑器以及集成开发环境(IDE)可以被用来建立、编辑和管理 PHP 文件。这些工具中的一部分被列在 » PHP 编辑器列表中。如果希望推荐其它的编辑器,请访问以上页面,并要求该页面的维护者将你推荐的编辑器加入到该列表中。使用支持语法高亮功能的编辑器会给开发带来很多帮助。

注解

关于文字处理器 诸如 StarOffice Writer、Microsoft Word 和 Abiword 的文字处理器不适合用来编辑 PHP 程序。如果希望用以上这些工具的某一种来处理脚本,必须保证将结果存成了纯文本格式,否则 PHP 将无法读取并运行这些脚本。

注解

关于 Windows 记事本 如果使用 Windows 记事本来编写 PHP 脚本,需要注意在保存文件时,文件的后缀名应该为 .php(记事本将自动在文件名后面加上 .txt 后缀,除非采取以下措施之一来避免这种情况)。当保存文件时,系统会让你指定文件的文件名,这时请将文件名加上引号(例如 “hello.php”)。或者,也可以点击“保存”对话框中的“保存类型”下拉菜单,并将设置改为“所有文件”。这样在输入文件名的时候就不用加引号了。

现在已经成功建立了一个简单的 PHP 脚本。还可以建立一个最著名的 PHP 脚本。调用函数 phpinfo(),将会看到很多有关自己系统有用的信息,以及预定义变量、已经加载的 PHP 模块和配置信息。请花一些时间来查看这些重要的信息。

例 #2 从 PHP 获取系统信息

<?php phpinfo(); ?>

实用的脚本

现在来编写一些更实用的脚本,比如检查浏览页面的访问者在用什么浏览器。要达到这个目的,需要检查用户的 agent 字符串,它是浏览器发送的 HTTP 请求的一部分。该信息被存储在一个变量中。在 PHP 中,变量总是以一个美元符开头。我们现在感兴趣的变量是 $_SERVER[‘HTTP_USER_AGENT’]。

注解

$_SERVER 是一个特殊的 PHP 保留变量,它包含了 web 服务器提供的所有信息,被称为超全局变量。请查阅本手册“超全局变量”中的有关内容以获取更多信息。这些特殊的变量是在 PHP » 4.1.0 版本引入的。在这之前使用 $HTTP_*_VARS 数组,如 $HTTP_SERVER_VARS。尽管现在已经不用了,但它们在新版本中仍然存在(参见“旧代码”一节中的注解)。

要显示该变量,只需简单地进行如下操作:

例 #1 打印一个变量(数组元素)

<?php
 echo $_SERVER['HTTP_USER_AGENT'];
?>

该脚本的输出可能是:

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

PHP 有很多种不同类型的变量。在以上例子中我们打印了一个数组的单元。数组是一类非常有用的变量。

$_SERVER 只是 PHP 自动全局化的变量之一。可以查阅“保留变量”一节来查看这些变量的列表,或者也可以通过上节例子中 phpinfo() 函数的输出来查看。

可以在一个 PHP 标识中加入多个 PHP 语句,也可以建立一个代码块来做比简单的 echo 更多的事情。例如,如果需要识别 Internet Explorer,可以进行如下操作:

例 #2 流程控制与函数的使用

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
    echo '正在使用 Internet Explorer。<br />';
}
?>

该脚本的输出可能是:

正在使用 Internet Explorer。<br />

这里要介绍一些新的原理。上面用了一个 if 语句。如果用户对 C 语言的基本语法比较熟悉,则应该对此很熟悉,否则,可能需要拿起任何一本 PHP 介绍性的书籍并阅读前面的两三个章节,或者也可以阅读本手册的“语言参考”一章。

需要介绍的第二个原理,是对 strpos() 函数的调用。 strpos() 是 PHP 的一个内置函数,其功能是在一个字符串中搜索另外一个字符串。例如我们现在需要在 $_SERVER[‘HTTP_USER_AGENT’](即所谓的 haystack)变量中寻找 ‘MSIE’。如果在这个 haystack 中该字符串(即所谓的 needle)被找到,则函数返回 needle 在 haystack 中相对开头的位置;如果没有,则返回 FALSE。如果该函数没有返回 FALSE,则 if 会将条件判断为 TRUE 并运行其花括号 {} 内的代码;否则,则不运行这些代码。可以自己尝试利用 if,else 以及其它的函数,例如 strtoupper() 和 strlen(),来建立类似的脚本。在本手册中相关的页面也包含有范例。如果对如何使用函数不是很确定,可以阅读手册中有关“如何阅读函数定义”和“函数”的有关章节。

以下我们进一步显示如何进出 PHP 模式,甚至是在一个 PHP 代码块的中间:

例 #3 混和 HTML 和 PHP 模式

<?php
 if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
<h3>strpos() 肯定没有返回假 (FALSE)</h3>
<p>正在使用 Internet Explorer</p>
<?php
 } else {
?>
<h3>strpos() 肯定返回假 (FALSE)</h3>
<center><b>没有使用 Internet Explorer</b></center>
<?php
 }
?>

该脚本的输出可能是:

<h3>strpos() 肯定没有返回假 (FALSE)</h3>
<p>正在使用 Internet Explorer</p>

和以上我们用一个 PHP 的 echo 语句来输出不同的是,我们跳出了 PHP 模式来直接写 HTML 代码。这里很值得注意的一点是,对于这两种情况而言,脚本的逻辑效率是相同的。在判断了 strpos() 函数的返回值是 TRUE 或是 FALSE,也就是判断了字符串 ‘MSIE’ 是否被找到之后,最终只有一个 HTML 块被发送给浏览者。

处理表单

PHP 一个很有用的特点体现在它处理 PHP 表单的方式。需要理解的非常重要的原理,是表单的任何元素都在 PHP 脚本中自动生效。请参阅本手册中“PHP 的外部变量”以获取关于在 PHP 中使用表单的详细信息及范例。以下是 HTML 表单的范例:

例 #1 一个简单的 HTML 表单

<form action="action.php" method="post">
 <p>姓名: <input type="text" name="name" /></p>
 <p>年龄: <input type="text" name="age" /></p>
 <p><input type="submit" /></p>
</form>

该表单中并没有什么特殊的地方,其中没有使用任何特殊的标识符。当用户填写了该表单并点击了提交按钮,页面 action.php 将被调用。在该文件中,可以加入如下内容:

例 #2 打印来自表单的数据

你好,<?php echo htmlspecialchars($_POST['name']); ?>
<?php echo (int)$_POST['age']; ?> 岁了。

该脚本的输出可能是:

你好,Joe。你 22 岁了。

除了 htmlspecialchars() 和 (int) 部分,这么做是显而易见的。 htmlspecialchars() 使得 HTML 之中的特殊字符被正确的编码,从而不会被使用者在页面注入 HTML 标签或者 Javascript代码。例如 age 字段,我们明确知道他是一个数值,因此我们将它转换 为一个 整形值(integer) 来自动的消除任何不必要的字符。你也可以使用PHP的 过滤(filter) 扩来自动的完成该工作。 PHP 将自动设置 $_POST[‘name’] 和 $_POST[‘age’] 变量。在这之前我们使用了超全局变量 $_SERVER,现在我们引入了超全局变量 $_POST,它包含了所有的 POST 数据。请注意我们的表单提交数据的方法(method)。如果使用了 GET 方法,那么表单中的信息将被储存到超全局变量 $_GET 中。如果并不关心请求数据的来源,也可以用超全局变量 $_REQUEST,它包含了所有 GET、POST、COOKIE 和 FILE 的数据。请参阅 import_request_variables() 函数。

也可以在 PHP 中处理 XForms 的输入,尽管可能更喜欢使用长久以来支持良好的 HTML 表单。XForms 目前还不适合初学者使用,但是用户可能对它感兴趣。手册中在“特点”一章有一节对如何处理从 XForum 接收到的数据进行了简短的介绍。

在新版本的 PHP 中使用旧的 PHP 代码

现在,PHP 已经发展成为一种流行的脚本语言,可以在很多公共的资源里找到可以在自己的脚本中重新利用的代码。PHP 语言的开发者为向下兼容性下了很多功夫,因此在新版本的 PHP 下,老版本的代码应该可以在不作任何改动的情况下(理想地)运行。不过实际上,还是必须对老的代码做一些改动。

有可能影响到老版本的代码的最重要的两点改动分别是:

  • 取消了旧的 $HTTP_*_VARS 数组(在函数或者方法中原本是全局变量)。PHP » 4.1.0 版本引入了如下超全局数组变量:$_GET、$_POST、$_COOKIE、$_SERVER、$_FILE、$_ENV、$_REQUEST 以及 $_SESSION。老的 $HTTP_*_VARS 数组,诸如 $HTTP_POST_VARS 等,从 PHP 3 就已经开始使用,它们仍然存在。自 PHP 5.0.0 起, 用 register_long_arrays 设置选项可禁用 长类型的 PHP 预定义变量数组。
  • 外部变量不再被默认注册为全局变量。也就是说,从 PHP » 4.2.0 版开始,php.ini 中的设置选项 register_globals 默认值变成了 off。建议用以上提到的超全局数组变量来访问这些值。但可能老的脚本、书籍以及教程都可能建立在该设置为 on 的基础上。如果该选项被设置为 on,则可以在 URL http://www.example.com/foo.php?id=42 中直接使用变量 $id。但不管被设置为 on 还是 off,$_GET[‘id’] 一直有效。

如果希望了解关于这些改动的细节,请参阅“预定义变量”一章以及其中的连接。

下一步做什么?

用现在掌握的知识,应该能够理解本手册中的大部分内容以及其中各式各样的脚本范例。在 php.net 网站的连接区 » http://www.php.net/links.php 能购获得其它更多的范例。

请查阅 PHP Conference 资料网站 » http://talks.php.net/ 以观看更多幻灯片,这些幻灯片展示了许多 PHP 其它的功能。

安装和配置

安装前需要考虑的事项

安装前,首先需要知道想用 PHP 来做什么。PHP 主要用在三个领域,分别在“PHP 能做什么”一节中进行了描述:

  • 网站和 web 应用程序(服务器端脚本)
  • 命令行脚本
  • 桌面(GUI)应用程序

在通常情况下,需要三样东西:PHP 自身、一个 web 服务器和一个 web 浏览器。可能已经有了一个 web 浏览器,并且根据操作系统的配置,也很可能已经有了一个 web 服务器(例如 Linux 和 MacOS 下的 Apache;Windows 下的 IIS)。也许在某个公司租用了 web 空间,这样,自己无需设置任何东西,仅需要编写 PHP 脚本,并上传到租用的空间中,然后在浏览器中查看结果。

如果需要自己配置服务器和 PHP,有两个方法将 PHP 连接到服务器上。对于很多服务器,PHP 均有一个直接的模块接口(也叫做 SAPI)。这些服务器包括 Apache、Microsoft Internet Information Server、Netscape 和 iPlanet 等服务器。其它很多服务器支持 ISAPI,即微软的模块接口(OmniHTTPd 就是个例子)。如果 PHP 不能作为模块支持 web 服务器,总是可以将其作为 CGI 或 FastCGI 处理器来使用。这意味着可以使用 PHP 的 CGI 可执行程序来处理所有服务器上的 PHP 文件请求。

如果对 PHP 命令行脚本感兴趣(例如在离线状态下,根据传递给脚本的参数,自动生成一些图片,或处理一些文本文件),总是需要命令行可执行程序。更多信息可以参考 PHP 的命令行模式。如果是这种情况,不需要服务器和浏览器。

还可以用 PHP 的 PHP-GTK 扩展来编写桌面图形界面应用程序。这与编写 web 页面完全不同,因为无需输出任何 HTML,而要管理窗口和窗口中的对象。关于 PHP-GTK 的更多信息,请» 访问专门为该扩展建立的网站。PHP-GTK 没有包含在官方发布的 PHP 中。

现在,本节开始说明如何在 Unix 和 Windows 的 web 服务器中配置服务器模块接口和 CGI 可执行程序。也将在下面几节中了解到有关命令行可执行程序安装的信息。

PHP 源代码包和二进制包可以在 » http://www.php.net/downloads.php 找到。建议选择一个最近的» 镜象服务器下载。

Unix 系统下的安装

Unix 系统下的 Apache 1.3.x

Unix 系统下的 Apache 2.x

Unix平台的Lighttpd 1.4

Sun Solaris 上的 Sun、iPlanet 和 Netscape 服务器

CGI 和命令行设置

HP-UX 平台的具体安装说明

在 OpenBSD 系统下的安装

在 Solaris 下的安装

Debian GNU/Linux 安装说明

Mac OS X 系统下的安装

使用软件包

使用内置的PHP

在Mac OS X上编译PHP

Windows 系统下的安装

Windows 安装程序

Windows Installer (PHP 5.2 and later)

Manual Installation Steps

Microsoft IIS

Microsoft IIS 5.1 and IIS 6.0

Microsoft IIS 7.0 and later

Microsoft Windows 下的 Apache 1.3.x

Apache 2.x on Microsoft Windows

Microsoft Windows 下的 Sun,iPlanet 和 Netscape 服务器

Microsoft Windows 下的 Sambar 服务器

Microsoft Windows 下的 Xitami

从源程序编译

Windows 下安装扩展库

Command Line PHP on Microsoft Windows

云计算平台上的安装

Microsoft Azure

Amazon EC2

FPM

安装

需求

FPM使用libevent来管理链接和进程信号. 至少需要安装libevent-1.4.11或者以上版本.

从源代码编译

编译PHP时需要 –enable-fpm 配置选项来激活FPM支持

以下为FPM编译的具体配置参数(全部为可选参数):

  • –with-libevent-dir - 指定libevent的安装路径
  • –with-fpm-user - 设置 FPM 运行的用户身份 (默认 - nobody).
  • –with-fpm-group - 设置 FPM 运行时的用户组 (默认 - nobody).

运行时配置

FPM 配置文件为 php-fpm.conf,其语法类似 php.ini

全局配置
pid

字符串 PID文件的位置. 默认为空.

error_log

字符串 错误日志的位置. 默认: 安装路径#INSTALL_PREFIX#/log/php-fpm.log.

log_level

字符串 错误级别. 可用级别为: alert(必须立即处理), error(错误情况), warning(警告情况), notice(一般重要信息), debug(调试信息). 默认: notice.

emergency_restart_threshold

整型 如果子进程在emergency_restart_interval设定的时间内收到该参数设定次数的SIGSEGV 或者 SIGBUS退出信息号,则FPM会重新启动。 0 表示 ‘关闭该功能’. 默认值: 0 (关闭).

emergency_restart_interval

mixed emergency_restart_interval用于设定平滑重启的间隔时间. 这么做有助于解决加速器中共享内存的使用问题. 可用单位: s(秒), m(分), h(小时), 或者 d(天). 默认单位: s(秒). 默认值: 0 (关闭).

process_control_timeout

mixed 设置子进程接受主进程复用信号的超时时间. 可用单位: s(秒), m(分), h(小时), 或者 d(天) 默认单位: s(秒). 默认值: 0.

daemonize

Boolean Operations — and, or, not 设置FPM在后台运行. 设置 ‘no’ 将 FPM 保持在前台运行用于调试. 默认值: yes.

运行配置

在FPM中,可以使用不同的设置来运行多个进程池。 这些设置可以针对每个进程池单独设置。

listen

字符串 设置接受FastCGI请求的地址. 可用格式为: ‘ip:port’, ‘port’, ‘/path/to/unix/socket’. 每个进程池都需要设置.

listen.backlog

整型 设置 listen(2) 的半连接队列长度. ‘-1’ 表示无限制. 默认值: -1.

listen.allowed_clients

字符串 设置允许连接到FastCGI的服务器IPV4地址. 等同于PHP FastCGI (5.2.2+)中的 FCGI_WEB_SERVER_ADDRS环境变量. 仅对TCP监听起作用. 每个地址是用逗号分隔. 如果没有设置或者为空,则允许任何服务器请求连接. 默认值: any.

listen.owner

字符串 如果使用,表示设置Unix套接字的权限. 在Linux中,读写权限必须设置,以便用于WEB服务器连接. 在很多BSD派生的系统中可以忽略权限允许自由连接. 默认值: 运行所使用的用户合租, 权限为0666.

listen.group

字符串 参见 listen.owner.

listen.mode

字符串 参见 listen.owner.

user

字符串 FPM 进程运行的Unix用户. 必须设置.

group

字符串 FPM 进程运行的Unix用户组. 如果没有设置,则默认用户的组被使用.

pm

字符串 设置进程管理器如何管理子进程. 可用值: static, dynamic. 必须设置.

static - 子进程的数量是固定的 (pm.max_children).

dynamic - 子进程的数量在下面配置的基础上动态设置: pm.max_children, pm.start_servers, pm.min_spare_servers, pm.max_spare_servers.

pm.max_children

整型 子进程的数量,pm 设置为 static 时表示创建的, pm 设置为 dynamic 时表示最大可创建的. 必须设置.

该选项设置可以同时提供服务的请求数限制. 类似 Apache 的 mpm_prefork 中 MaxClients 的设置和 普通PHP FastCGI中的 PHP_FCGI_CHILDREN 环境变量.

pm.start_servers

整型 设置启动时创建的子进程数目. 仅在 pm 设置为 dynamic 时使用. 默认值: min_spare_servers + (max_spare_servers - min_spare_servers) / 2.

pm.min_spare_servers

整型 设置空闲服务进程的最低数目. 仅在 pm 设置为 dynamic 时使用. 必须设置.

pm.max_spare_servers

整型 设置空闲服务进程的最大数目. 仅在 pm 设置为 dynamic 时使用. 必须设置.

pm.max_requests

整型 设置每个子进程重生之前服务的请求数. 对于可能存在内存泄漏的第三方模块来说是非常有用的. 如果设置为 ‘0’ 则一直接受请求. 等同于 PHP_FCGI_MAX_REQUESTS 环境变量. 默认值: 0.

pm.status_path

字符串 FPM状态页面的网址. 如果没有设置, 则无法访问状态页面. 默认值: none.

ping.path

字符串 FPM监控页面的ping网址. 如果没有设置, 则无法访问ping页面. 该页面用于外部检测FPM是否存活并且可以响应请求. 请注意必须以斜线开头 (/).

ping.response

字符串 用于定义ping请求的返回相应. 返回为 HTTP 200 的 text/plain 格式文本. 默认值: pong.

request_terminate_timeout

设置单个请求的超时中止时间. 该选项可能会对php.ini设置中的’max_execution_time’因为某些特殊原因没有中止运行的脚本有用. 设置为 ‘0’ 表示 ‘Off’. Available units: s(econds)(default), m(inutes), h(ours), or d(ays). Default value: 0.

request_slowlog_timeout

mixed 当一个请求该设置的超时时间后,就会将对应的PHP调用堆栈信息完整写入到慢日志中. 设置为 ‘0’ 表示 ‘Off’. 可用单位: s(秒)(默认), m(分), h(小时), 或者 d(天). 默认值: 0.

slowlog

字符串 慢请求的记录日志. 默认值: #INSTALL_PREFIX#/log/php-fpm.log.slow.

rlimit_files

整型 设置文件打开描述符的rlimit限制. 默认值: 系统定义值.

rlimit_core

整型 设置核心rlimit最大限制值. 可用值: ‘unlimited’ 、0或者正整数. 默认值: 系统定义值.

chroot

字符串 启动时的Chroot目录. 所定义的目录需要是绝对路径. 如果没有设置, 则chroot不被使用.

chdir

字符串 设置启动目录,启动时会自动Chdir到该目录. 所定义的目录需要是绝对路径. 默认值: 当前目录,或者/目录(chroot时).

catch_workers_output

布尔型 重定向运行过程中的stdout和stderr到主要的错误日志文件中. 如果没有设置, stdout 和 stderr 将会根据FastCGI的规则被重定向到 /dev/null . 默认值: 空.

你还可以在为一个运行池传递附加的环境变量,或者更新PHP的配置值. 你可以在 php-fpm.conf 中下如下面的配置参数来做到:

例 #1 给运行池传递环境变量和设置PHP的配置值

env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp

php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/fpm-php.www.log
php_admin_flag[log_errors] = on
php_admin_value[memory_limit] = 32M

PHP配置值通过 php_value 或者 php_flag 设置,并且会覆盖以前的值. 请注意 disable_functions 或者 disable_classes 在 php.ini 之中定义的值不会被覆盖掉, 但是会将新的设置附加在原有值的后面. 使用 php_admin_value 或者 php_admin_flag 定义的值,不能被PHP代码中的 ini_set() 覆盖.

FPM (FastCGI 进程管理器) 用于替换PHP FastCGI的大部分附加功能,对于高负载网站是非常有用的。

它的功能包括:

  • 支持平滑停止/启动的高级进程管理功能;
  • 可以工作于不同的uid/gid/chroot环境下,并监听不同的端口和使用不同的php.ini配置文件(可取代safe_mode的设置);
  • stdout 和 stderr 日志记录;
  • 在发生意外情况的时候能够重新启动并缓存被破坏的opcode;
  • 文件上传优化支持;
  • “慢日志” - 记录脚本 (不仅记录文件名,还记录PHP backtrace信息,可以使用ptrace或者类似工具读取和分析远程进程的运行数据) 运行所导致的异常缓慢;
  • fastcgi_finish_request() - 特殊功能:用于在请求完成和刷新数据后,继续在后台执行耗时的工作 (录入视频转换、统计处理等);
  • 动态/静态子进程产生;
  • 基本SAPI运行状态信息 (类似Apache的 mod_status);
  • 基于php.ini的配置文件.

待处理

研究ptrace

PECL

PECL 扩展库安装

PECL 安装介绍

» PECL 是通过 » PEAR 打包系统来的 PHP 扩展库仓库,本章内容示范了怎样取得并安装 PECL 扩展。

以下指南中假定 /your/phpsrcdir/ 是 PHP 源程序的路径,extname 是 PECL 扩展库的名字。自己根据实际情况调整。此外还假定用户熟悉 » pear 命令。 PEAR 手册里 pear 命令的信息同样适用于 pecl

要使用共享扩展库,必须经过编译,安装,然后加载。以下说明的方法提供了怎样编译和安装扩展库的各种指导,但并不会自动加载它们。可以通过将其包括在 php.ini 中用 extension PHP 指令加载,或者 用 dl() 函数。

当编译 PHP 模块时,拥有各种工具(autoconf,automake,libtool 等)的已知好使的版本很重要。所需工具和所需版本的详情见» 匿名 Git 说明

下载 PECL 扩展库

下载 PECL 扩展库有几种方法,如:

  • pecl install extname 命令会自动下载扩展代码, 所以在这种情况下不需要再次下载。

  • » http://pecl.php.net/ PECL 网站包括有 PHP 开发组提供的不同扩展库的信息。这里的信息包括:更新记录,版本说明,需求,以及其它信息。

  • pecl download extname PECL 网站中列出的 PECL 扩展库的发行版本可以用 » pear 命令来下载和安装。也可以指明具体的修正版。

  • SVN 大多数 PECL 扩展库也在 SVN 中。其 web 页面见 be seen at » http://svn.php.net/viewvc/pecl/。要直接从 SVN 中下载,用以下命令:

    $ svn checkout http://svn.php.net/repository/pecl/extname/trunk extname
    
  • Windows 下载 目前 PHP 项目没有为 Windows 下 PECL 扩展编译二进制文件。 要在 Windows 下编译 PHP,请阅读有关章节。

在 Windows 上安装 PHP 扩展

在 Windows 上有两种加载 PHP 扩展的方式:把扩展编译进 PHP,或者加载 DLL。加载预编译的扩展是更简单更被推荐的方式。

To load an extension, you need to have it available as a ”.dll” file on your system. All the extensions are automatically and periodically compiled by the PHP Group (see next section for the download).

To compile an extension into PHP, please refer to building from source documentation.

To compile a standalone extension (aka a DLL file), please refer to building from source documentation. If the DLL file is available neither with your PHP distribution nor in PECL, you may have to compile it before you can start using the extension.

哪里找扩展?

PHP extensions are usually called “php_*.dll” (where the star represents the name of the extension) and they are located under the “PHPext” (“PHPextensions” in PHP 4) folder.

PHP ships with the extensions most useful to the majority of developers. They are called “core” extensions.

However, if you need functionality not provided by any core extension, you may still be able to find one in PECL. The PHP Extension Community Library (PECL) is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions.

If you have developed an extension for your own uses, you might want to think about hosting it on PECL so that others with the same needs can benefit from your time. A nice side effect is that you give them a good chance to give you feedback, (hopefully) thanks, bug reports and even fixes/patches. Before you submit your extension for hosting on PECL, please read http://pecl.php.net/package-new.php.

下载哪个扩展?

Many times, you will find several versions of each DLL:

Different version numbers (at least the first two numbers should match) Different thread safety settings Different processor architecture (x86, x64, ...) Different debugging settings etc. You should keep in mind that your extension settings should match all the settings of the PHP executable you are using. The following PHP script will tell you all about your PHP settings:

Example #1 phpinfo() call <?php phpinfo(); ?> Or from the command line, run:

drive:\pathtophpexecutablephp.exe -i

载入一个扩展

最常见的方式是在 php.ini 配置文件里包含一个 PHP 扩展。 请注意很多扩展已经在 php.ini 里了,你需要的仅仅是移除分号来激活它们。

;extension=php_extname.dll extension=php_extname.dll However, some web servers are confusing because they do not use the php.ini located alongside your PHP executable. To find out where your actual php.ini resides, look for its path in phpinfo():

Configuration File (php.ini) Path C:WINDOWS Loaded Configuration File C:Program FilesPHP5.2php.ini After activating an extension, save php.ini, restart the web server and check phpinfo() again. The new extension should now have its own section.

Resolving problems

If the extension does not appear in phpinfo(), you should check your logs to learn where the problem comes from.

If you are using PHP from the command line (CLI), the extension loading error can be read directly on screen.

If you are using PHP with a web server, the location and format of the logs vary depending on your software. Please read your web server documentation to locate the logs, as it does not have anything to do with PHP itself.

Common problems are the location of the DLL, the value of the ” extension_dir” setting inside php.ini and compile-time setting mismatches.

If the problem lies in a compile-time setting mismatch, you probably didn’t download the right DLL. Try downloading again the extension with the right settings. Again, phpinfo() can be of great help.

用 PEAR 编译共享 PECL 扩展库

PECL 使建立共享 PHP 扩展库更容易。用 » pecl 命令这样做:

$ pecl install extname

这将下载 extname 的源代码,编译之,并将 extname.so 安装到 extension_dir 中。然后 extname.so 就可以通过 php.ini 加载了。

默认情况下,pecl 命令不会安装标记为 alpha 或 beta 状态的包。如果没有 stable 包可用,也可以用以下命令安装一个 beta 包:

$ pecl install extname-beta

也可以用此命令安装一个指定的版本:

$ pecl install extname-0.1

注解

After enabling the extension in php.ini, restarting the web service is required for the changes to be picked up.

用 phpize 编译共享 PECL 扩展库

有时候不能用 pecl 安装命令。这可能是因为在防火墙后面,或者是因为想要安装的扩展库还没有 PECL 兼容的包,例如 SVN 中尚未发布的扩展库。如果要编译这种扩展库,可以用更底层的编译工具来手工进行编译。

phpize 命令是用来准备 PHP 扩展库的编译环境的。下面例子中,扩展库的源程序位于 extname 目录中:

 $ cd extname
 $ phpize
 $ ./configure
 $ make
# make install

成功的安装将创建 extname.so 并放置于 PHP 的扩展库目录中。需要调整 php.ini,加入 extension=extname.so 这一行之后才能使用此扩展库。

If the system is missing the phpize command, and precompiled packages (like RPM’s) are used, be sure to also install the appropriate devel version of the PHP package as they often include the phpize command along with the appropriate header files to build PHP and its extensions.

Execute phpize –help to display additional usage information.

php-config

php-config is a simple shell script for obtaining information about the installed PHP configuration.

When compiling extensions, if you have multiple PHP versions installed, you may specify for which installation you’d like to build by using the –with-php-config option during configuration, specifying the path of the respective php-config script.

The list of command line options provided by the php-config script can be queried anytime by running php-config with the -h switch:

Usage: /usr/local/bin/php-config [OPTION]
Options:
  --prefix            [...]
  --includes          [...]
  --ldflags           [...]
  --libs              [...]
  --extension-dir     [...]
  --include-dir       [...]
  --php-binary        [...]
  --php-sapis         [...]
  --configure-options [...]
  --version           [...]
  --vernum            [...]

Command line options

Option Description
–prefix Directory prefix where PHP is installed, e.g. /usr/local
–includes List of -I options with all include files
–ldflags LD Flags which PHP was compiled with
–libs Extra libraries which PHP was compiled with
–extension-dir Directory where extensions are searched by default
–include-dir Directory prefix where header files are installed by default
–php-binary Full path to php CLI or CGI binary
–php-sapis Show all SAPI modules available
–configure-options Configure options to recreate configuration of current PHP installation
–version PHP version
–vernum PHP version as integer

将 PECL 扩展库静态编译入 PHP

有时可能需要将扩展库静态编译到 PHP 中。这需要将扩展库源程序放入 php-src/ext/ 目录中去并告诉 PHP 编译系统来生成其配置脚本。

$ cd /your/phpsrcdir/ext
$ pecl download extname
$ gzip -d < extname.tgz | tar -xvf -
$ mv extname-x.x.x extname

这将产生以下目录:

/your/phpsrcdir/ext/extname

此时强制 PHP 重新生成配置脚本,然后正常编译 PHP:

$ cd /your/phpsrcdir
$ rm configure
$ ./buildconf --force
$ ./configure --help
$ ./configure --with-extname --enable-someotherext --with-foobar
$ make
$ make install

注解

要运行“buildconf”脚本,需要 autoconf 2.13 和 automake 1.4+(更新版本的 autoconf 也许能工作,但不被支持)。

是否用 –enable-extname 或 –with-extname 取决于扩展库。通常不需要外部库文件的扩展库使用 –enable。要确认的话,在 buildconf 之后运行:

$ ./configure --help | grep extname

还有问题?

阅读 FAQ

有些问题比其它的更为普遍。最常见的列在 PHP 常见问题 中,是本手册的一部分。

其它问题

如果还卡着,PHP 安装邮件列表中的人可能会帮你。应该先查看归档,也许有人已经回答了另一个人提出的和你相同的问题。归档可以从支持页 » http://www.php.net/support.php 访问到。要订阅 PHP 安装邮件列表,发送一封空邮件去 » php-install-subscribe@lists.php.net。邮件列表地址是 » php-install@lists.php.net

如果想从邮件列表中取得帮助,请准确给出有关你的环境的必要细节(哪个操作系统,PHP 的版本,哪个 web 服务器,是否以 CGI 方式还是以服务器模块方式运行 PHP,安全模式,等等),并给出足够的代码让别人能重现和测试你碰到的问题。

错误报告

如果你觉得自己发现了一个 PHP 的 bug,请提出报告。PHP 开发人员也许还不知道有问题,除非你报告了,否则有可能不会被修正。可以通过错误跟踪系统 » http://bugs.php.net/ 来报告错误。请不要在邮件列表或私人信件中发送错误报告。错误跟踪系统也可以用来提出对新特性的要求。

在提交错误报告之前请先阅读 » 怎样报告错误

运行时配置

配置文件

配置文件(php.ini)在 PHP 启动时被读取。对于服务器模块版本的 PHP,仅在 web 服务器启动时读取一次。对于 CGI 和 CLI 版本,每次调用都会读取。

php.ini 的搜索路径如下(按顺序):

  • SAPI 模块所指定的位置(Apache 2 中的 PHPIniDir 指令,CGI 和 CLI 中的 -c 命令行选项,NSAPI 中的 php_ini 参数,THTTPD 中的 PHP_INI_PATH 环境变量)
  • PHPRC 环境变量。Before PHP 5.2.0, this was checked after the registry key mentioned below.
  • As of PHP 5.2.0, the location of the php.ini file can be set for different versions of PHP. The following registry keys are examined in order: [HKEY_LOCAL_MACHINESOFTWAREPHPx.y.z], [HKEY_LOCAL_MACHINESOFTWAREPHPx.y] and [HKEY_LOCAL_MACHINESOFTWAREPHPx], where x, y and z mean the PHP major, minor and release versions. If there is a value for IniFilePath in any of these keys, the first one found will be used as the location of the php.ini (Windows only).
  • [HKEY_LOCAL_MACHINESOFTWAREPHP] 内 IniFilePath 的值(Windows 注册表位置)。
  • 当前工作目录(对于 CLI)
  • web 服务器目录(对于 SAPI 模块)或 PHP 所在目录(Windows 下其它情况)
  • Windows 目录(C:windows 或 C:winnt),或 –with-config-file-path 编译时选项指定的位置
  • 如果存在 php-SAPI.ini(SAPI 是当前所用的 SAPI 名称,因此实际文件名为 php-cli.ini 或 php-apache.ini 等),则会用它替代 php.ini。SAPI 的名称可以用 php_sapi_name() 来测定。

由扩展库处理的 php.ini 指令,其文档分别在各扩展库的页面。内核配置选项见附录。不过也许不是所有的 PHP 指令都在手册中有文档说明。要得到自己的 PHP 版本中的配置指令完整列表,请阅读 php.ini 文件,其中都有注释。此外,也许从 Git 得到的» 最新版 php.ini 也有帮助。

Example #1 php.ini 例子

; any text on a line after an unquoted semicolon (;) is ignored
[php] ; section markers (text within square brackets) are also ignored
; Boolean values can be set to either:
;    true, on, yes
; or false, off, no, none
register_globals = off
track_errors = yes

; you can enclose strings in double-quotes
include_path = ".:/usr/local/lib/php"

; backslashes are treated the same as any other character
include_path = ".;c:\php\lib"

自 PHP 5.1.0 起,有可能在 .ini 文件内引用已存在的 .ini 变量。例如:open_basedir = ${open_basedir} ”:/new/dir”。

.user.ini files

.user.ini files

Since PHP 5.3.0, PHP includes support for .htaccess-style INI files on a per-directory basis. These files are processed only by the CGI/FastCGI SAPI. This functionality obsoletes the PECL htscanner extension. If you are using Apache, use .htaccess files for the same effect.

In addition to the main php.ini file, PHP scans for INI files in each directory, starting with the directory of the requested PHP file, and working its way up to the current document root (as set in $_SERVER[‘DOCUMENT_ROOT’]). In case the PHP file is outside the document root, only its directory is scanned.

Only INI settings with the modes PHP_INI_PERDIR and PHP_INI_USER will be recognized in .user.ini-style INI files.

Two new INI directives, user_ini.filename and user_ini.cache_ttl control the use of user INI files.

user_ini.filename sets the name of the file PHP looks for in each directory; if set to an empty string, PHP doesn’t scan at all. The default is .user.ini.

user_ini.cache_ttl controls how often user INI files are re-read. The default is 300 seconds (5 minutes).

Where a configuration setting may be set

These modes determine when and where a PHP directive may or may not be set, and each directive within the manual refers to one of these modes. For example, some settings may be set within a PHP script using ini_set(), whereas others may require php.ini or httpd.conf.

For example, the output_buffering setting is PHP_INI_PERDIR therefore it may not be set using ini_set(). However, the display_errors directive is PHP_INI_ALL therefore it may be set anywhere, including with ini_set().

Definition of PHP_INI_* modes

Mode Meaning
PHP_INI_USER Entry can be set in user scripts (like with ini_set()) or in the Windows registry Since PHP 5.3, entry can be set in .user.ini
PHP_INI_PERDIR Entry can be set in php.ini, .htaccess or httpd.conf
PHP_INI_SYSTEM Entry can be set in php.ini or httpd.conf
PHP_INI_ALL Entry can be set anywhere

怎样修改配置设定

PHP 运行于 Apache 模块方式

当使用 PHP 作为 Apache 模块时,也可以用 Apache 的配置文件(例如 httpd.conf)和 .htaccess 文件中的指令来修改 PHP 的配置设定。需要有“AllowOverride Options”或“AllowOverride All”权限才可以。

有几个 Apache 指令可以使用户在 Apache 配置文件内部修改 PHP 的配置。哪些指令属于 PHP_INI_ALL,PHP_INI_PERDIR 或 PHP_INI_SYSTEM 中的哪一个,请参考附录中的 php.ini 配置选项列表。

php_value name value

设定指定的值。只能用于 PHP_INI_ALL 或 PHP_INI_PERDIR 类型的指令。要清除先前设定的值,把 value 设为 none。

注解

不要用 php_value 设定布尔值。应该用 php_flag(见下面)。

php_flag name on|off

用来设定布尔值的配置指令。仅能用于 PHP_INI_ALL 和 PHP_INI_PERDIR 类型的指令。

php_admin_value name value

设定指定的指令的值。不能用于 .htaccess 文件。任何用 php_admin_value 设定的指令都不能被 .htaccess 或 virtualhost 中的指令覆盖。要清除先前设定的值,把 value 设为 none。

php_admin_flag name on|off

用来设定布尔值的配置指令。不能用于 .htaccess 文件。任何用 php_admin_flag 设定的指令都不能被 .htaccess 或 virtualhost 中的指令覆盖。

Example #1 Apache 配置例子

<IfModule mod_php5.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag engine on
</IfModule>
<IfModule mod_php4.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag engine on
</IfModule>

警告

PHP 常量不存在于 PHP 之外。例如在 httpd.conf 中不能使用 PHP 常量如 E_ALL 或 E_NOTICE 来设定 error_reporting 指令,因为其无意义,实际等于 0。应该用相应的掩码值来替代。这些常量可以在 php.ini 中使用。

通过 Windows 注册表修改 PHP 配置

在 Windows 下运行 PHP 时,可以用 Windows 注册表以目录为单位来修改配置。配置值存放于注册表项 HKLMSOFTWAREPHPPer Directory Values 下面,子项对应于路径名。例如对于目录 c:inetpubwwwroot 的配置值会存放于 HKLMSOFTWAREPHPPer Directory Valuescinetpubwwwroot 项下面。其中的设定对于任何位于此目录及其任何子目录的脚本都有效。项中的值的名称是 PHP 配置指令的名字,值的数据是字符串格式的指令值。值中的 PHP 常量不被解析。不过只有可修改范围是 PHP_INI_USER 的配置值可以用此方法设定,PHP_INI_PERDIR 的值就不行。

其它接口下的 PHP

无论怎样运行 PHP,都可以在脚本中通过 ini_set() 而在运行时修改某个值。更多信息见手册中 ini_set() 的页面。

如果对自己系统中的配置设定及其当前值的完整列表感兴趣,可以运行 phpinfo() 函数并查看其结果的页面。也可以在运行时用 ini_get() 或 get_cfg_var() 取得个别配置指令的值。

语言参考

基本语法

从 HTML 中分离

当 PHP 解析一个文件时,会寻找开始和结束标记,标记告诉 PHP 开始和停止解释其中的代码。此种方式的解析可以使 PHP 嵌入到各种不同的文档中,凡是在一对开始和结束标记之外的内容都会被 PHP 解析器忽略。大多数情况下 PHP 都是嵌入在 HTML 文档中的,如下例所示:

<p>This is going to be ignored.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored.</p>

还可以用更高级的结构:

Example #1 高级分离术

<?php
if ($expression) {
   ?>
   <strong>This is true.</strong>
   <?php
} else {
   ?>
   <strong>This is false.</strong>
   <?php
}
?>

上例可正常工作,因为当 PHP 碰到结束标记 ?> 时,就简单地将其后的内容原样输出( 除非其后紧接着一个新行,参见指令分隔符 )直到碰到下一个开始标记为止。当然,上面的例子很做作,但是对输出大块的文本而言,脱离 PHP 解析模式通常比将所有内容用 echo 或者 print 输出更有效率。

可以在 PHP 中使用四对不同的开始和结束标记。其中两种,<?php ?> 和 <script language=”php”> </script> 总是可用的。另两种是短标记和 ASP 风格标记,可以在 php.ini 配置文件中打开或关闭。尽管有些人觉得短标记和 ASP 风格标记很方便,但移植性较差,通常不推荐。

注解

此外注意如果将 PHP 嵌入到 XML 或 XHTML 中则需要使用 <?php ?> 以保持符合标准。

Example #2 PHP 开始和结束标记:

1.  <?php echo 'if you want to serve XHTML or XML documents, do like this'; ?>

2.  <script language="php">
       echo 'some editors (like FrontPage) don\'t
             like processing instructions';
    </script>

3.  <? echo 'this is the simplest, an SGML processing instruction'; ?>
    <?= expression ?> This is a shortcut for "<? echo expression ?>"

4.  <% echo 'You may optionally use ASP-style tags'; %>
    <%= $variable; # This is a shortcut for "<% echo . . ." %>

上例中的 1 和 2 总是可用的,其中 1 是最常用,并建议使用的。

短标记(上例 3)仅在通过 php.ini 配置文件中的指令 short_open_tag 打开后才可用,或者在 PHP 编译时加入了 –enable-short-tags 选项。

ASP 风格标记(上例 4)仅在通过 php.ini 配置文件中的指令 asp_tags 打开后才可用。

注解

在以下情况应避免使用短标记:开发需要发行的程序或者库,或者在用户不能控制的服务器上开发。因为目标服务器可能不支持短标记。为了代码的移植及发行,确保不要使用短标记。

指令分隔符

同 C 或 Perl 一样,PHP 需要在每个语句后用分号结束指令。一段 PHP 代码中的结束标记隐含表示了一个分号;在一个 PHP 代码段中的最后一行可以不用分号结束。如果后面还有新行,则代码段的结束标记包含了行结束。

<?php
   echo "This is a test";
?>

<?php echo "This is a test" ?>

<?php echo 'We omitted the last closing tag';

注解

文件末尾的 PHP 代码段结束标记可以不要,有些情况下当使用 include 或者 require 时省略掉会更好些,这样不期望的空白符就不会出现在文件末尾,之后仍然可以输出响应标头。在使用输出缓冲时也很便利,就不会看到由包含文件生成的不期望的空白符。

注释

PHP 支持 C,C++ 和 Unix Shell 风格(Perl 风格)的注释。例如:

<?php
   echo "This is a test"; // This is a one-line c++ style comment
   /* This is a multi line comment
      yet another line of comment */
   echo "This is yet another test";
   echo 'One Final Test'; # This is a one-line shell-style comment
?>

单行注释仅仅注释到行末或者当前的 PHP 代码块,视乎哪个首先出现。这意味着在 // ... ?> 或者 # ... ?> 之后的 HTML 代码将被显示出来:?> 跳出了 PHP 模式并返回了 HTML 模式,// 或 # 并不能影响到这一点。如果启用了 asp_tags 配置选项,其行为和 // %> 或 # %> 相同。不过,</script> 标记在单行注释中不会跳出 PHP 模式:

<h1>This is an <?php # echo "simple";?> example.</h1>
<p>The header above will say 'This is an example'.

C 风格的注释在碰到第一个 */ 时结束。要确保不要嵌套 C 风格的注释。试图注释掉一大块代码时很容易出现该错误。

<?php
 /*
    echo "This is a test"; /* This comment will cause a problem */
 */
?>

类型

简介

PHP 支持8种基本的数据类型。

四种标量类型:

  • boolean (布尔型)
  • integer (整型)
  • float (浮点型, 也称作 double)
  • string (字符串)

两种复合类型:

  • array (数组)
  • object (对象)

最后是三种特殊类型:

  • resource
  • NULL
  • callable

为了确保代码的易读性,本手册还介绍了一些伪类型:

  • mixed
  • number
  • callback
  • $....

可能还会读到一些关于“双精度(double)”类型的参考。实际上 double 和 float 是相同的,由于一些历史的原因,这两个名称同时存在。

变量的类型通常不是由程序员设定的,确切地说,是由 PHP 根据该变量使用的上下文在运行时决定的。

注解

如果想查看某个表达式的值和类型,用 var_dump()。

如果只是想得到一个易读懂的类型的表达方式用于调试,用 gettype()。要查看某个类型,不要用 gettype(),而用 is_type 函数。以下是一些范例:

<?php
$a_bool = TRUE;   // a boolean
$a_str  = "foo";  // a string
$a_str2 = 'foo';  // a string
$an_int = 12;     // an integer

echo gettype($a_bool); // prints out:  boolean
echo gettype($a_str);  // prints out:  string

// If this is an integer, increment it by four
if (is_int($an_int)) {
    $an_int += 4;
}

// If $bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool)) {
    echo "String: $a_bool";
}
?>

如果要将一个变量强制转换为某类型,可以对其使用强制转换或者 settype() 函数。

注意变量根据其当时的类型在特定场合下会表现出不同的值。更多信息见类型戏法。此外,你还可以参考 PHP 类型比较表看不同类型相互比较的例子。

布尔型

这是最简单的类型。boolean 表达了真值,可以为 TRUEFALSE

注解

布尔类型是 PHP 4 引进的。

语法

要指定一个布尔值,使用关键字 TRUEFALSE。两个都不区分大小写。

<?php
$foo = True; // assign the value TRUE to $foo
?>

通常你用某些运算符返回 boolean 值,并将其传递给控制流程。

<?php
// == 是一个操作符,它检测两个变量是否相等,并返回一个布尔值
if ($action == "show_version") {
   echo "The version is 1.23";
}
// 这样做是不必要的...
if ($show_separators == TRUE) {
   echo "<hr>\n";
}
// ...因为可以使用下面这种简单的方式:
if ($show_separators) {
    echo "<hr>\n";
}
?>

转换为布尔值

要明确地将一个值转换成 boolean,用 (bool) 或者 (boolean) 来强制转换。但是很多情况下不需要用强制转换,因为当运算符,函数或者流程控制结构需要一个 boolean 参数时,该值会被自动转换。

参见类型戏法。

当转换为 boolean 时,以下值被认为是 FALSE:

the 布尔值 FALSE 自身 the 整型值 0 (零) the 浮点型值 0.0 (零) 空 字符串, 以及 字符串 “0” 不包括任何元素的数组 不包括任何成员变量的对象(仅PHP 4.0 适用) 特殊类型 NULL (包括尚未设定的变量) 从没有任何标记(tags)的XML文档生成的SimpleXML 对象 所有其它值都被认为是 TRUE(包括任何资源)。

警告

-1 和其它非零值(不论正负)一样,被认为是 TRUE!

<?php
var_dump((bool) "");        // bool(false)
var_dump((bool) 1);         // bool(true)
var_dump((bool) -2);        // bool(true)
var_dump((bool) "foo");     // bool(true)
var_dump((bool) 2.3e5);     // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array());   // bool(false)
var_dump((bool) "false");   // bool(true)
?>

整型

一个 integer 是集合 Z = {..., -2, -1, 0, 1, 2, ...} 中的一个数。

参见

  • 任意长度整数 / GMP
  • 浮点数
  • 任意精度数学库 / BCMath
语法

整型值可以使用十进制,十六进制或八进制表示,前面可以加上可选的符号(- 或者 +)。

八进制表示数字前必须加上 0(零),十六进制表示数字前必须加上 0x。

例 #1 整数文字表达

<?php
  $a = 1234; // 十进制数
  $a = -123; // 负数
  $a = 0123; // 八进制数 (等于十进制 83)
  $a = 0x1A; // 十六进制数 (等于十进制 26)
?>

整型(integer)的形式描述:

decimal     : [1-9][0-9]*
            | 0

hexadecimal : 0[xX][0-9a-fA-F]+

octal       : 0[0-7]+

integer     : [+-]?decimal
            | [+-]?hexadecimal
            | [+-]?octal

整型数的字长和平台有关,尽管通常最大值是大约二十亿(32 位有符号)。PHP 不支持无符号整数。Integer值的字长可以用常量 PHP_INT_SIZE 来表示,自 PHP 4.4.0 和 PHP 5.0.5后,最大值可以用常量PHP_INT_MAX来表示。

警告

如果向八进制数传递了一个非法数字(即 8 或 9),则后面其余数字会被忽略。

例 #2 八进制数的怪事

<?php
  var_dump(01090); // 八进制 010 = 十进制 8
?>
整数溢出

如果给定的一个数超出了 integer 的范围,将会被解释为 float。同样如果执行的运算结果超出了 integer 范围,也会返回 float。

<?php
 $large_number =  2147483647;
 var_dump($large_number);
// 输出为:int(2147483647)

$large_number =  2147483648;
var_dump($large_number);
// 输出为:float(2147483648)

// 同样也适用于十六进制表示的整数: 从 2^31 到 2^32-1:
var_dump( 0xffffffff );
// 输出: float(4294967295)

// 不适用于大于 2^32-1 的十六进制表示的数:
var_dump( 0x100000000 );
// 输出: int(2147483647)

$million = 1000000;
$large_number =  50000 * $million;
var_dump($large_number);
// 输出: float(50000000000)
?>

警告

不幸的是 PHP 中有个 bug,因此当有负数参与时结果并不总是正确。例如当运算 -50000 * $million 时结果是 -429496728。不过当两个运算数都是正数时就没问题。

这个问题已经在 PHP 4.1.0 中解决了。

PHP 中没有整除的运算符。1/2 产生出 float 0.5。可以总是舍弃小数部分,或者使用 round() 函数。

<?php
 var_dump(25/7);         // float(3.5714285714286)
 var_dump((int) (25/7)); // int(3)
 var_dump(round(25/7));  // float(4)
?>
转换为整型

要明确地将一个值转换为 integer,用 (int) 或 (integer) 强制转换。不过大多数情况下都不需要强制转换,因为当运算符,函数或流程控制需要一个 integer 参数时,值会自动转换。还可以通过函数 intval() 来将一个值转换成整型。

参见

类型转换的判别.

从布尔值转换

FALSE 将产生出 0(零),TRUE 将产生出 1(壹)。

从浮点数转换

当从浮点数转换成整数时,将向零取整。

如果浮点数超出了整数范围(通常为 +/- 2.15e+9 = 2^31),则结果不确定,因为没有足够的精度使浮点数给出一个确切的整数结果。在此情况下没有警告,甚至没有任何通知!

警告

决不要将未知的分数强制转换为 integer,这样有时会导致不可预料的结果。

<?php
 echo (int) ( (0.1+0.7) * 10 ); // 显示 7!
?>

参见

关于浮点数精度的警告。

从字符串转换

参见

字符串转换为数字

从其它类型转换

警告

没有定义从其它类型转换为整型的行为。不要依赖任何可见的行为,因为它会未加通知地改变。

浮点型

浮点数(也叫浮点数,双精度数或实数)可以用以下任一语法定义:

<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>

浮点数的形式表示:

LNUM          [0-9]+
DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})

浮点数的字长和平台相关,尽管通常最大值是 1.8e308 并具有 14 位十进制数字的精度(64 位 IEEE 格式)。

警告

关于浮点数精度的警告

显然简单的十进制分数如同 0.1 或 0.7 不能在不丢失一点点精度的情况下转换为内部二进制的格式。这就会造成混乱的结果:例如,floor((0.1+0.7)*10) 通常会返回 7 而不是预期中的 8,因为该结果内部的表示其实是类似 7.9。

这和一个事实有关,那就是不可能精确的用有限位数表达某些十进制分数。例如,十进制的 1/3 变成了 0.3。

所以永远不要相信浮点数结果精确到了最后一位,也永远不要比较两个浮点数是否相等。如果确实需要更高的精度,应该使用任意精度数学函数或者 gmp 函数。

转换为浮点数

如果希望了解有关何时和如何将字符串转换成浮点数的信息,请查阅“将字符串转换为数值”一节。对于其它类型的值,其情况类似于先将值转换成整型,然后再转换成浮点。请参阅“转换为整型”一节以获取更多信息。自 PHP 5 起,如果试图将对象转换为浮点数,会发出一条 E_NOTICE 错误。

字符串

一个字符串 就是由一系列的字符组成,因此,一个字符就是一个字节。这就是说,一个字节只能有256种不同的变化,这也暗示了PHP无 法原生支持Unicode 。 更多信息可参考函数 utf8_encode()和 utf8_decode()。

注解

一个很长的字符串是没有问题的,PHP对于字符串; 而对字符串长度的限制只和运行PHP程序的该台计 算机的内存大小有关。

语法

一个字符串 通过下面的4种方法来定义:

  • 单引号
  • 双引号
  • heredoc 语法结构
  • nowdoc 语法结构 (自PHP 5.3.0以后)
单引号

定义一个字符串 的最简单的方法是用单引号把它包围起来 (标点符号 ‘)。

如果想要输出一个单引号,需在它的前面加个反斜线 ()。在单引号前或在字符串的结尾处 想要输出反斜线,输入两条 (\)。注意,如果在任何其它的字符前加了反斜线,反斜线将会被直接输出。

注解

不像双引号 和heredoc语法结构, 在单引号字符串中的变量 和特殊含义的字符将 不会 被替换。

<?php
  echo 'this is a simple string';

  // 可以录入多行
  echo 'You can also have embedded newlines in
     strings this way as it is
     okay to do';

  // 输出: Arnold once said: "I'll be back"
  echo 'Arnold once said: "I\'ll be back"';

  // 输出: You deleted C:\*.*?
  echo 'You deleted C:\\*.*?';

  // 输出: You deleted C:\*.*?
  echo 'You deleted C:\*.*?';

  // 输出: This will not expand: \n a newline
  echo 'This will not expand: \n a newline';

  // 输出: Variables do not $expand $either
  echo 'Variables do not $expand $either';
?>
双引号

如果字符串是包围在双引号(”)中, PHP将对一些特殊的字符进行解析:

Escaped characters

序列 含义
n 换行 (LF or 0x0A (10) in ASCII)
r 回车 (CR or 0x0D (13) in ASCII)
t 水平方向的 tab(HT or 0x09 (9) in ASCII)
v 竖直方向的 tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
f 换页 (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\ 反斜线
$ 美金dollar标记
双引号
[0-7]{1,3} 符合该表达式顺序的字符串是一个八进制的字符
x[0-9A-Fa-f]{1,2} 符合该表达式顺序的字符串是一个十六进制的字符

和单引号 字符串一样, 如果输出上述之外的字符,反斜线会被打印出来。 PHP5.1.1以 前,\{$var} 中的反斜线还不会被显示出来。

用双引号定义的字符串最重要的特征是变量会被解析,更多信息见字符串解析。

Heredoc结构

第三种定义字符串的方法是用heredoc句法结构:<<<。在该提示 符后面,要定义个标识符,然后是一个新行。接下来是字符串 本身,最后要用前面定义的标识符作为结束标志。

结束时所引用的标识符必须在一行的开始位置, 而且,标识符的命名也要像其它标签一样遵守PHP的规则:只能包含 字母、数字和下划线,并且必须以字母和下划线作为开头。

警告

要注意的是结束标识符这行除了 可能有一个分号(;)外,绝对不能包括 其它字符。这意味着标识符不能缩进,分号的前后也不能有任何空白或tabs。更重要的是结束标识符的前面必须是个被本地 操作系统认可的新行标签,比如在UNIX和Mac OS X系统中是n ,而结束标识符(可能有个分号)的后面也必须跟个 新行标签。

如果不遵守该规则导致结束标签不“干净”,PHP将认为它不是结束标识符而继续寻找。如果在文件结束前也没有找到一个正确的结束标识符,PHP将会在最后一 行产生一个句法错误。

Heredocs结构不能用来初始化class,而从PHP 5.3以后,则该限制只能用在包含变量的情况下。

例 #1 非法的示例

<?php
class foo {
    public $bar = <<<EOT
bar
EOT;
}
?>

Heredoc结构就象是没有使用双引号的双引号字符串, 这就是说在heredoc结构中引号不用被替换,但是上文中列出的字符 (n等)也可使用。 变量将被替换,但在heredoc结构中字符串表达复杂变量时,要格外小 心。

例 #2 Heredoc结构的字符串示例

<?php
$str = <<<EOD
例 of string
spanning multiple lines
using heredoc syntax.
EOD;

/* 含有变量的更复杂示例 */
class foo
{
    var $foo;
    var $bar;

    function foo()
    {
        $this->foo = 'Foo';
        $this->bar = array('Bar1', 'Bar2', 'Bar3');
    }
}

$foo = new foo();
$name = 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

以上例程会输出:

My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

也可以把Heredoc结构用在函数参数中来传输数据:

例 #3 Heredoc结构在参数中的示例

<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>

在PHP 5.3.0以后,也可以用Heredoc结构来初始化静态变量和类的属性和常量:

例 #4 使用Heredoc结构来初始化静态值

<?php
// 静态变量
function foo()
{
    static $bar = <<<LABEL
Nothing in here...
LABEL;
}

// 类的常量、属性
class foo
{
    const BAR = <<<FOOBAR
Constant 例
FOOBAR;

    public $baz = <<<FOOBAR
Property 例
FOOBAR;
}
?>

在PHP 5.3.0中还在Heredoc结构中用双引号来声明标志符:

例 #5 在heredoc结构中使用双引号

<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>
Nowdoc结构

就象heredoc结构类似于双引号字符串,Nowdoc结构是类似于单引号字符串的。Nowdoc结构很象heredoc结构,但是 nowdoc不进行解析操作 。 这种结构很适合用在不需要进行转义的PHP代码和其它大段文本。与SGML的 <![CDATA[ ]]> 结构是用来声明大段的不用解析的文本类似,nowdoc结构也有相同的特征。

一个nowdoc结构也用和heredocs结构一样的标记 <<<, 但是跟在后面的标志符要用 单引号括起来,就像<<<’EOT’这样。heredocs结构的所有规则也同样适用于nowdoc结 构,尤其是结束标志符的规则。

例 #6 Nowdoc结构字符串示例

<?php
$str = <<<'EOD'
例 of string
spanning multiple lines
using nowdoc syntax.
EOD;

/* 含有变量的更复杂的示例 */
class foo
{
    public $foo;
    public $bar;

    function foo()
    {
        $this->foo = 'Foo';
        $this->bar = array('Bar1', 'Bar2', 'Bar3');
    }
}

$foo = new foo();
$name = 'MyName';

echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41
EOT;
?>

以上例程会输出:

My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41

例 #7 表态数据的示例

<?php
class foo {
    public $bar = <<<'EOT'
bar
EOT;
}
?>
变量解析

当字符串用双引号或heredoc结构定义时,其中的变 量将会被解析。

这里共有两种语法规则:一种简单 规则,一种复杂规 则。简单的句法规则是最常用和最方便的, 它可以用最少的代码在一个字符串中加入变量, 数组 值,或 对象属性。

复杂的句法规则是在PHP4以后加入的,被花括号包围的表达式是其明显标记。

简单句法规则

当PHP解析器遇到一个美元符号 ($) , 它会和其它很多解析器一样,去尽量形成一个合法的变量名。可以用花括 号来明确变量名的界线。

<?php
$beer = 'Heineken';
echo "$beer's taste is great"; //有效;单引号"'"是非法的变量名组成元素
echo "He drank some $beers"; //无效;字母s是有效的变量名组成元素,但是这里的变量是$beer
echo "He drank some ${beer}s"; // 有效
echo "He drank some {$beer}s"; // 有效
?>

类似的,一个 数组 索引或一个 对象 属性也可被解析。数组索引要用方括号 (]) 来表示边际, 对象属性则是和上述的变量规则相同。

<?php
// 下面的例子是在字符串中引用数组
// 当数组处于字符串外部时,要把数组的值用括号括起来且不要用花括号{ }

// 显示所有错误
error_reporting(E_ALL);

$fruits = array('strawberry' => 'red', 'banana' => 'yellow');

// 有效;但是注意在字符串外面不能这样引用数组
echo "A banana is $fruits[banana].";

// 有效
echo "A banana is {$fruits['banana']}.";

// 有效,但是PHP会先寻找常量banana
echo "A banana is {$fruits[banana]}.";

// 无效,要用花括号,这里将会产生一个解析错误
echo "A banana is $fruits['banana'].";

// 有效
echo "A banana is " . $fruits['banana'] . ".";

// 有效
echo "This square is $square->width meters broad.";

// 无效,解决方法见复杂结构
echo "This square is $square->width00 centimeters broad.";
?>

如果想要表达更复杂的结构,请用复杂句法规则。

复杂句法规则

复杂句法规则不是结构复杂而命名,而是因为它可以使用复杂的表达式。

任何想用在字符串中标量变量,数组变量或对象属性都可使用这种方法。 只需简单地像在字符串以外的地方那样写出表达式, 然后用花括号{和 }把它括起来。 由于 { 无法被转义,只有 $ 要紧挨着 {才会被认出来,可以用 {$ 来表达 {$。下面的示例可以更好的解释:

<?php
// 显示所有错误
error_reporting(E_ALL);

$great = 'fantastic';

// 无效,输出: This is { fantastic}
echo "This is { $great}";

// 有效,输出: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// 有效
echo "This square is {$square->width}00 centimeters broad.";

// 有效
echo "This works: {$arr[4][3]}";

// 这是错误的表达式,因为就象$foo[bar] 的格式不能在字符串以外的地方使用一样。
// 换句话说,只有在PHP能找到常量foo 的前提下才会正常工作;这里会产生一个E_NOTICE (undefined constant)级别的错误。
echo "This is wrong: {$arr[foo][3]}";

// 有效,当在字符串中使用多重数组时,一定要用括号将它括起来
echo "This works: {$arr['foo'][3]}";

// 有效
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName():
{${getName()}}";

echo "This is the value of the var named by the return value of
\$object->getName(): {${$object->getName()}}";

// 无效,输出: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

也可以在字符串中用变量来调用类的属性。

<?php
 class foo {
     var $bar = 'I am bar.';
 }

 $foo = new foo();
 $bar = 'bar';
 $baz = array('foo', 'bar', 'baz', 'quux');
 echo "{$foo->$bar}\n";
 echo "{$foo->$baz[1]}\n";
?>

以上例程会输出:

I am bar.
I am bar.

注解

函数、行为、类的静态变量和类的常量只有在PHP 5以后才可在 {$} 中使用。然而,只有在用返回的值作为名 称的变量存在的情况下才会进行处理,只单一使用花括号 ({}) 无法处理从函数或行为的返回值或从类的常量或静态变量的返 回值。

<?php
// 显示所有错误
error_reporting(E_ALL);

class beers {
   const softdrink = 'rootbeer';
   public static $ale = 'ipa';
}

$rootbeer = 'A & W';
$ipa = 'Alexander Keith\'s';

// 有效,输出: I'd like an A & W
echo "I'd like an {${beers::softdrink}}\n";

// 也有效,输出: I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}\n";
?>
存取和修改字符串中的字符

字符串中的字符可以通过一个以0为开始的,用类似数组结构中的方括号包含对应的数字来查找和修改,比如 $str[42], 可以把 字符串想像数组 。 函数 substr() 和 substr_replace()可以用来实现多于一个字符 的情况。

注解

字符串为了同样的目的也可以用花括号,比如 $str{42},但是, 在 PHP 5.3.0中不推荐使用这种格式,应该用方括号,就像 $str[42]。

警告

方括号中的数字超出范围将会产生空白。非整数类型被转换成整数,非整数类型转变成整数,非法类型会产生一个 E_NOTICE级别错误,负数在写入时会产生一个E_NOTICE,但读 取的是空字符串。被指定的字符串只有第一个字符可用,空字符串用指定为空字节。下面为英文原文: Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NUL byte.

例 #8 一些字符串例子

<?php
// 取得字符串的第一个字符
$str = 'This is a test.';
$first = $str[0];

// 取得字符串的第三个字符
$third = $str[2];

// 取得字符串的最后一个字符
$str = 'This is still a test.';
$last = $str[strlen($str)-1];

// 修改字符串的最后一个字符
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';

?>

注解

用 [] 或 {} 存取其它类型的变量只会返回 NULL.

有用的函数和操作符

字符串可以用’.’ (点) 操作符连接起来, 注意 ‘+’ (加号) 操作符 没有 这个功能。 更多信息参考 字符串操作符 。

对于字符串 的操作有很多有用的函数。

可以参考 字符串函数 了解大部分函数, 高级的查找&替换功能可以参考 正则表达式函数 或 Perl类型的正则 表达式函数。

另外还有URL字符串的函数, 也有加密/解密字符串的函数。 (mcrypt 和 mhash).

最后,可以参考 字符类型函数。

转换成字符串

一个值可以通过在其前面加上(string)或用 strval()函数来转变成 字符串。 在一个需要字符串的表达式中,字符串会自动转变,比如在使用函数 echo 或 print 时, 或在一个变量和一个 字符串 进行比较时,就会发生这种转变 类型 和 类型转换 可以更好的解释下面的事情,也可参考函 数 settype() 。

一个boolean TRUE 值被转换成 字符串”1”。 Boolean FALSE 被转换成”” (空的字符串)。 这种转变可以在 boolean 和 字符串 之间往返进行。

一个 整数 或 浮点数 被转变为数字的字面样式的字符串 (包括 浮点数中的指数部分),使用指数计数法的浮点数 (4.1E+6)也可转变。

注解

在脚本场所(category LC_NUMERIC)定义了小数点,更多可以参考函数 setlocale()。

数组转换成 字符串 “Array”,因此, echo 和 print c无法显示出该数组的值。如果显示一个数组值,可以用 echo $arr[‘foo’]这种结构,更多内容见下文。

在PHP 4中对象被转换成 字符串 “Object”, 果为了调试原因需要打印出对象的值,方法见正文。为了得到对象的类的名称,可以用 get_class() 函数。 在PHP5中, 可以用 __toString 。

资源总会被转变成”Resource id #1”这种结构的 字符串 , 其中的 1 是PHP分配给该资源的独特数字。不用过多关注这种结构,它马上要转变了。为了得到一个 resource类型,可以用函数 get_resource_type()。

NULL 总是被转变成空的字符串。

如上面所说的,直接把数组, 对象或 资源 转换成 字符串 不会得到超出其自身的更多信息。可以使用函数 print_r() 和 var_dump() 列出这些类型的内容。

大部分的PHP值可以转变成 字符串s 来长期储存,这被称作串行化,可以用函数 serialize() 来实现。 如果PHP引擎设定支持 WDDX , PHP值也可储存成XML格式。

字符串转变成数字

当一个字符串 被用在了一个数字的环境中,结果和类型如下:

如果字符串 没有包含 ‘.’,’e’或’E’ 并且数字值符合整数类型的限定 ( PHP_INT_MAX定义的), 这个 字符串 可被认定是一个 integer, 在其它情况下被认定为一个float。

字符串的开始部分给定了它的值,如果 字符串 以合法的数字开始,这个数字可直接使用。 否则,值就 是 0 (零)。 合法数值由符号,后面跟着一个或多个数字(可能有个小数点),再跟着可选的指数符号如’e’ 或 ‘E’,后面跟着一个或多个数字。

<?php
$foo = 1 + "10.5";                // $foo is float (11.5)
$foo = 1 + "-1.3e3";              // $foo is float (-1299)
$foo = 1 + "bob-1.3e3";           // $foo is integer (1)
$foo = 1 + "bob3";                // $foo is integer (1)
$foo = 1 + "10 Small Pigs";       // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1;          // $foo is float (11)
$foo = "10.0 pigs " + 1.0;        // $foo is float (11)
?>

更多信息可以参考Unix手册中的strtod(3)。

本节中的示例可以通过复制/粘贴到下面的代码中来显示:

<?php
echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n";
?>

不要想像在C语言中的那样,通过一个整数转换得到相应字符,使用函数 ord() 和 chr() 实现ASCII码和字符间的转换。

数组

PHP 中的 数组 实际上是一个有序映射。映射是一种把 values 关联到 keys 的类型。此类型在很多方面做了优化,因此可以把它当成真正的数组,或列表(向量),散列表(是映射的一种实现),字典,集合,栈,队列以及更多可能性。数组元素的值也可以是另一个数组。树形结构和多维数组也是允许的。

解释这些结构超出了本手册的范围,但对于每种结构至少会提供一个例子。要得到这些结构的更多信息,建议参考有关此广阔主题的其它著作。

语法
定义数组 array()

可以用 array() 语言结构来新建一个 array。它接受任意数量用逗号分隔的 键(key) => 值(value) 对:

array(  key =>  value
     , ...
     )
// (key) 可是是一个 整数(integer)  字符串(string)
// (value) 可以是任意类型的值
<?php
$arr = array("foo" => "bar", 12 => true);

echo $arr["foo"]; // bar
echo $arr[12];    // 1
?>

以上例程在PHP 5.3中的输出:

string(1) "b"
bool(true)
string(1) "b"
bool(true)
string(1) "a"
bool(true)
string(1) "b"
bool(true)

以上例程在PHP 5.4中的输出:

string(1) "b"
bool(true)

Warning: Illegal string offset '1.0' in /tmp/t.php on line 7
string(1) "b"
bool(false)

Warning: Illegal string offset 'x' in /tmp/t.php on line 9
string(1) "a"
bool(false)
string(1) "b"
bool(false)

key 可以是 integer 或者 string。如果key是一个 integer 的标准表示,则被解释为整数(例如 “8” 将被解释为 8,而 “08” 将被解释为 “08”)。key 中的浮点数被取整为 integer。在 PHP 中索引数组与关联 数组 是相同的,它们都可以同时包含 整型 和 字符串 的下标。

值可以是任意的 PHP 类型。

<?php
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));

echo $arr["somearray"][6];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42
?>

如果对给出的值没有指定键名,则取当前最大的整数索引值,而新的键名将是该值加一。如果指定的键名已经有了值,则该值会被覆盖。

<?php
// 这个数组与下面的数组相同 ...
array(5 => 43, 32, 56, "b" => 12);

// ...
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>

警告

自 PHP 4.3.0 起,上述的索引生成方法改变了。如今如果给一个当前最大键名是负值的数组添加一个新值,则新生成的的索引将为零(0)。以前新生成的索引为当前最大索引加一,和正值的索引相同。

使用 TRUE 作为键名将使 integer 1 成为键名。使用 FALSE 作为键名将使 integer 0 成为键名。使用 NULL 作为键名将等同于使用空字符串。使用空字符串作为键名将新建(或覆盖)一个用空字符串作为键名的值,这和用空的方括号不一样。

不能用数组和对象作为键(key)。这样做会导致一个警告:Illegal offset type。

用方括号的语法新建/修改

可以通过明示地设定值来改变一个现有的数组。

这是通过在方括号内指定键名来给数组赋值实现的。也可以省略键名,在这种情况下给变量名加上一对空的方括号(“[]”):

$arr[key] = value;
$arr[] = value;
// key 可以是 integer 或 string
// value 可以是任意类型的值

如果 $arr 还不存在,将会新建一个。这也是一种定义数组的替换方法。要改变一个值,只要给它赋一个新值。如果要删除一个键名/值对,要对它用 unset()。

<?php
$arr = array(5 => 1, 12 => 2);

$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script

$arr["x"] = 42; // This adds a new element to
                // the array with key "x"

unset($arr[5]); // This removes the element from the array

unset($arr);    // This deletes the whole array
?>

注意这里所使用的最大整数键名不一定当前就在数组中。它只要在上次数组重新生成索引后曾经存在过就行了。以下面的例子来说明:

<?php
// 创建一个简单的数组
$array = array(1, 2, 3, 4, 5);
print_r($array);

// 现在删除其中的所有元素,但保持数组本身不变:
foreach ($array as $i => $value) {
    unset($array[$i]);
}
print_r($array);

// 添加一个单元(注意新的键名是 5,而不是你可能以为的 0)
$array[] = 6;
print_r($array);

// 重新索引:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>

以上例程会输出:

Array
(
   [0] => 1
   [1] => 2
   [2] => 3
   [3] => 4
   [4] => 5
)
Array
(
)
Array
(
   [5] => 6
)
Array
(
   [0] => 6
   [1] => 7
)
实用函数

有很多操作数组的函数,参见数组函数一节。

<?php
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');
*/

$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>

foreach 控制结构是专门用于数组的。它提供了一个简单的方法来遍历数组。

数组做什么和不做什么
为什么 $foo[bar] 错了?

应该始终在用字符串表示的数组索引上加上引号。例如用 $foo[‘bar’] 而不是 $foo[bar]。但是为什么 $foo[bar] 错了呢?可能在老的脚本中见过如下语法:

<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>

这样是错的,但可以正常运行。那么为什么错了呢?原因是此代码中有一个未定义的常量(bar)而不是字符串(’bar’-注意引号),而 PHP 可能会在以后定义此常量,不幸的是你的代码中有同样的名字。它能运行,是因为 PHP 自动将裸字符串(没有引号的字符串且不对应于任何已知符号)转换成一个其值为该裸字符串的正常字符串。例如,如果没有常量定义为 bar,PHP 将把它替代为 ‘bar’ 并使用之。

注解

这并不意味着总是给键名加上引号。用不着给键名为常量或变量的加上引号,否则会使 PHP 不能解析它们。

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
   echo "\nChecking $i: \n";
   echo "Bad: " . $array['$i'] . "\n";
   echo "Good: " . $array[$i] . "\n";
   echo "Bad: {$array['$i']}\n";
   echo "Good: {$array[$i]}\n";
}
?>

以上例程会输出:

Checking 0:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad:
Good: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad:
Good: 1

Checking 1:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad:
Good: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad:
Good: 2

演示此行为的更多例子:

<?php
// Show all errors
error_reporting(E_ALL);

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// Correct
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrect.  This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// This defines a constant to demonstrate what's going on.  The value 'veggie'
// is assigned to a constant named fruit.
define('fruit', 'veggie');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]";      // Hello apple

// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";

// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>

当打开 error_reporting 来显示 E_NOTICE 级别的错误(例如将其设为 E_ALL)时将看到这些错误。默认情况下 error_reporting 被关闭不显示这些。

和在语法一节中规定的一样,在方括号(“[”和“]”)之间必须有一个表达式。这意味着可以这样写:

<?php
echo $arr[somefunc($bar)];
?>

这是一个用函数返回值作为数组索引的例子。PHP 也可以用已知常量,可能之前已经见过

<?php
$error_descriptions[E_ERROR]   = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

注意 E_ERROR 也是个合法的标识符,就和第一个例子中的 bar 一样。但是上一个例子实际上和如下写法是一样的:

<?php
$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

因为 E_ERROR 等于 1, 等等.

那么为什么这样做不好?

也许有一天,PHP 开发小组可能会想新增一个常量或者关键字,或者用户可能希望以后在自己的程序中引入新的常量,那就有麻烦了。例如已经不能这样用 empty 和 default 这两个词了,因为他们是保留字。

注解

重申一次,在双引号字符串中,不给索引加上引号是合法的因此 “$foo[bar]”是合法的(“合法”的原文为valid。在实际测试中,这么做确实可以访问数组的该元素,但是会报一个常量未定义的notice。无论如何,强烈建议不要使用$foo[bar]这样的写法,而要使用$foo[‘bar’]来访问数组中元素。–haohappy注)。至于为什么参见以上的例子和字符串中的变量解析中的解释。

转换为数组

对于任意类型: integer, float, string, boolean and resource,如果将一个值转换为数组,将得到一个仅有一个元素的数组(其下标为 0),该元素即为此标量的值。换句话说, (array)$scalarValue 与 array($scalarValue) 完全一样。

If an object is converted to an array, the result is an array whose elements are the object’s properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a ‘*’ prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:

<?php

class A {
   private $A; // This will become '\0A\0A'
}

class B extends A {
   private $A; // This will become '\0B\0A'
   public $AA; // This will become 'AA'
}

var_dump((array) new B());
?>

The above will appear to have two keys named ‘AA’, although one of them is actually named ‘0A0A’.

将 NULL 转换到 数组(array) 会得到一个空的数组。

比较

可能使用 array_diff() 和数组运算符来比较数组。

例子

PHP 中的数组类型有非常多的用途,因此这里有一些例子展示数组的完整威力。

<?php
// This:
$a = array( 'color' => 'red',
           'taste' => 'sweet',
           'shape' => 'round',
           'name'  => 'apple',
           4        // key will be 0
         );

$b = array('a', 'b', 'c');

// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';

// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4), and $b will be the array
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>

例 #1 Using array()

<?php
// Array as (property-)map
$map = array( 'version'    => 4,
             'OS'         => 'Linux',
             'lang'       => 'english',
             'short_tags' => true
           );

// strictly numerical keys
$array = array( 7,
               8,
               0,
               156,
               -10
             );
// this is the same as array(0 => 7, 1 => 8, ...)

$switching = array(         10, // key = 0
                   5    =>  6,
                   3    =>  7,
                   'a'  =>  4,
                           11, // key = 6 (maximum of integer-indices was 5)
                   '8'  =>  2, // key = 8 (integer!)
                   '02' => 77, // key = '02'
                   0    => 12  // the value 10 will be overwritten by 12
                 );

// empty array
$empty = array();
?>

例 #2 集合

<?php
$colors = array('red', 'blue', 'green', 'yellow');

foreach ($colors as $color) {
    echo "Do you like $color?\n";
}
?>

以上例程会输出:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

直接改变数组的值在 PHP 5 中可以通过引用传递来做到。之前的版本需要需要采取变通的方法:

例 #3 集合

<?php
// PHP 5
foreach ($colors as &$color) {
    $color = strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */

// Workaround for older versions
foreach ($colors as $key => $color) {
   $colors[$key] = strtoupper($color);
}

print_r($colors);
?>

以上例程会输出:

Array
(
   [0] => RED
   [1] => BLUE
   [2] => GREEN
   [3] => YELLOW
)

本例生成一个下标从1开始的数组。This example creates a one-based array.

例 #4 下标从1开始的数组

<?php
$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

以上例程会输出:

Array
(
   [1] => 'January'
   [2] => 'February'
   [3] => 'March'
)

例 #5 填充数组

<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
    $files[] = $file;
}
closedir($handle);
?>

数组是有序的。也可以使用不同的排序函数来改变顺序。更多信息参见数组函数。可以用 count() 函数来数出数组中元素的个数。

例 #6 数组排序

<?php
sort($files);
print_r($files);
?>

因为数组中的值可以为任意值,也可是另一个数组。这样可以产生递归或多维数组。

例 #7 递归和多维数组

<?php
$fruits = array ( "fruits"  => array ( "a" => "orange",
                                      "b" => "banana",
                                      "c" => "apple"
                                    ),
                 "numbers" => array ( 1,
                                      2,
                                      3,
                                      4,
                                      5,
                                      6
                                    ),
                 "holes"   => array (      "first",
                                      5 => "second",
                                           "third"
                                    )
               );

// Some examples to address values in the array above
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>

数组(Array) 的赋值总是会涉及到值的拷贝。使用 引用操作符 通过引用来拷贝数组。

<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2, 3)

$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>

对象

对象初始化

要创建一个新的对象 object, 使用 new 语句实例化一个类:

<?php
class foo
{
   function do_foo()
   {
       echo "Doing foo.";
   }
}

$bar = new foo;
$bar->do_foo();
?>

详细讨论参见手册中 类与对象 章节。

转换为对象

如果将一个对象转换成对象,它将不会有任何变化。如果其它任何类型的值被转换成对象,将会实例化一个内置类 stdClass 的对象。如果该值为 NULL,则新的实例为空。数组转换成对象将使键名成为属性名并具有相对应的值。对于任何其它的值,名为 scalar 的成员变量将包含该值。

<?php
$obj = (object) 'ciao';
echo $obj->scalar;  // outputs 'ciao'
?>

资源类型

资源是一种特殊变量,保存了到外部资源的一个引用。资源是通过专门的函数来建立和使用的。所有这些函数及其相应资源类型见附录。

注解

资源类型是 PHP 4 引进的。

参见 get_resource_type()。

转换为资源

由于资源类型变量保存有为打开文件、数据库连接、图形画布区域等的特殊句柄,因此将其它类型的值转换为资源没有意义。

释放资源

由于 PHP4 Zend 引擎引进了引用计数系统,可以自动检测到一个资源不再被引用了(和 Java 一样)。这种情况下此资源使用的所有外部资源都会被垃圾回收系统释放。因此,很少需要手工释放内存。 Thanks to the reference-counting system introduced with PHP 4’s Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.

注解

持久数据库连接比较特殊,它们不会被垃圾回收系统销毁。参见数据库永久连接一章。

NULL

特殊的 NULL 值表示一个变量没有值。NULL 类型唯一可能的值就是 NULL。

注解

NULL 类型是 PHP 4 引进的。

在下列情况下一个变量被认为是 NULL:

  • 被赋值为 NULL。
  • 尚未被赋值。
  • 被 unset()。
语法

NULL 类型只有一个值,就是大小写不敏感的关键字 NULL(你可以写成NULL,也可以写成null)。

<?php
$var = NULL;
?>

参见 is_null() 和 unset()。

转换到 NULL

将一个变量转换为 null 类型将会删除该变量并且unset它的值。

Callbacks

Callbacks can be denoted by callable type hint as of PHP 5.4. This documentation used callback type information for the same purpose.

Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.

Passing

A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0. As of PHP 5.2.3, it is also possible to pass ‘ClassName::methodName’.

Apart from common user-defined function, create_function() can also be used to create an anonymous callback function. As of PHP 5.3.0 it is possible to also pass a closure to a callback parameter.

Example #1 Callback function examples

<?php

// An example callback function
function my_callback_function() {
   echo 'hello world!';
}

// An example callback method
class MyClass {
   static function myCallbackMethod() {
       echo 'Hello World!';
   }
}

// Type 1: Simple callback
call_user_func('my_callback_function');

// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod'));

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
   public static function who() {
       echo "A\n";
   }
}

class B extends A {
   public static function who() {
       echo "B\n";
   }
}

call_user_func(array('B', 'parent::who')); // A
?>

Example #2 Callback example using a Closure

<?php
// Our closure
$double = function($a) {
    return $a * 2;
};

// This is our range of numbers
$numbers = range(1, 5);

// Use the closure as a callback here to
// double the size of each element in our
// range
$new_numbers = array_map($double, $numbers);

print implode(' ', $new_numbers);
?>

以上例程会输出:

2 4 6 8 10

注解

In PHP 4, it was necessary to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.

注解

在函数中注册有多个回调内容时(如使用 call_user_func() 与 call_user_func_array()),如在前一个回调中有未捕获的异常,其后的将不再被调用。

本文档中使用的伪类型

mixed

mixed 说明一个参数可以接受多种不同的(但并不必须是所有的)类型。

例如 gettype() 可以接受所有的 PHP 类型, str_replace() 可以接受字符串和数组。

number

number 说明一个参数可以是 integer 或者 float。

callback

有些诸如 call_user_function() 或 usort() 的函数接受用户自定义的函数作为一个参数。Callback 函数不仅可以是一个简单的函数,它还可以是一个对象的方法,包括静态类的方法。

一个 PHP 函数用函数名字符串来传递。可以传递任何内置的或者用户自定义的函数,除了语言结构如 array(), echo, empty(), eval(), exit(), isset(), list(), print 和 unset()。

一个对象的方法以数组的形式来传递,数组的下标 0 指明对象名,下标 1 指明方法名。

对于没有实例化为对象的静态类,要传递其方法,将数组 0 下标指明的对象名换成该类的名称即可。

除了普通的用户定义的函数外,也可以使用 create_function()来创建一个匿名的回调函数(callback)。

Example #1 回调函数(callback)示例

<?php

// 普通的回调函数
function my_callback_function() {
   echo 'hello world!';
}

// 回调方法
class MyClass {
   static function myCallbackMethod() {
       echo 'Hello World!';
   }
}

// Type 1: Simple callback
call_user_func('my_callback_function');

// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod'));

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
   public static function who() {
       echo "A\n";
   }
}

class B extends A {
   public static function who() {
       echo "B\n";
   }
}

call_user_func(array('B', 'parent::who')); // A
?>

注解

在 PHP4 中,必须使用引用来创建一个指向实际object,而不是它的一个拷贝。详情请见引用的解释。 In PHP4, it was necessary to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.

void

void 作为返回类型意味着函数的返回值是无用的。void作为参数列表意味着函数不接受任何参数。

...

在函数原型中,$... 表示等等的意思。当一个函数可以接受任意个参数时使用此变量名。

类型转换的判别

PHP 在变量定义中不需要(或不支持)明确的类型定义;变量类型是根据使用该变量的上下文所决定的。也就是说,如果把一个字符串值赋给变量 var,var 就成了一个字符串。如果又把一个整型值赋给 var,那它就成了一个整数。

PHP 的自动类型转换的一个例子是加号“+”。如果任何一个操作数是浮点数,则所有的操作数都被当成浮点数,结果也是浮点数。否则操作数会被解释为整数,结果也是整数。注意这并没有改变这些操作数本身的类型;改变的仅是这些操作数如何被求值以及表达式本身的类型。

<?php
$foo = "0";  // $foo 是字符串 (ASCII 48)
$foo += 2;   // $foo 现在是一个整数 (2)
$foo = $foo + 1.3;  // $foo 现在是一个浮点数 (3.3)
$foo = 5 + "10 Little Piggies"; // $foo 是整数 (15)
$foo = 5 + "10 Small Pigs";     // $foo 是整数 (15)
?>

如果上面两个例子看上去古怪的话,参见字符串转换为数值。

如果要强制将一个变量当作某种类型来求值,参见类型强制转换一节。如果要改变一个变量的类型,参见 settype()。

如果想要测试本节中任何例子的话,可以用 var_dump() 函数。

注解

自动转换为 数组 的行为目前没有定义。

Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:

<?php
$a    = 'car'; // $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?>

请参阅访问和修改字符串中的字符一节以获取更多信息。

类型强制转换

PHP 中的类型强制转换和 C 中的非常像:在要转换的变量之前加上用括号括起来的目标类型。

<?php
$foo = 10;   // $foo is an integer
$bar = (boolean) $foo;   // $bar is a boolean
?>

允许的强制转换有:

  • (int), (integer) - 转换为 整型(integer)
  • (bool), (boolean) - 转换为 布尔型(boolean)
  • (float), (double), (real) - 转换为 浮点型(float)
  • (string) - 转换为 字符串(string)
  • (binary) - 转换为二进制 字符串(string) (PHP 6)
  • (array) - 转换为 数组(array)
  • (object) - 转换为 对象(object)
  • (unset) - 转换为 NULL (PHP 5)
  • (binary) 转换会在结果前面加上前缀’b’,PHP 5.2.1 新增。

注意在括号内允许有空格和制表符,所以下面两个例子功能相同:

<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>

将 字符串(string)文字和变量转换为二进制 字符串(string):

<?php
$binary = (binary)$string;
$binary = b"binary string";
?>
<?php
$foo = 10;            // $foo 是一个整数
$str = "$foo";        // $str 是一个字符串
$fst = (string) $foo; // $fst 也是一个字符串

// 输出 "they are the same"
if ($fst === $str) {
   echo "they are the same";
}
?>

有时在类型之间强制转换时确切地会发生什么可能不是很明显。更多信息见如下小节:

  • 转换为布尔型
  • 转换为整型
  • 转换为浮点型
  • 转换为字符串
  • 转换为数组
  • 转换为对象
  • 转换为资源
  • 转换为 NULL
  • 类型比较表

变量

基础

PHP 中的变量用一个美元符号后面跟变量名来表示。变量名是区分大小写的。

变量名与 PHP 中其它的标签一样遵循相同的规则。一个有效的变量名由字母或者下划线开头,后面跟上任意数量的字母,数字,或者下划线。按照正常的正则表达式,它将被表述为:

'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

注解

在此所说的字母是 a-z,A-Z,以及 ASCII 字符从 127 到 255(0x7f-0xff)。

注解

$this 是一个特殊的变量,它不能被赋值。

Tip

参见

Userland Naming Guide。

有关变量的函数信息见变量函数。

<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var";      // 输出 "Bob, Joe"

$4site = 'not yet';     // 非法变量名;以数字开头
$_4site = 'not yet';    // 合法变量名;以下划线开头
$i站点is = 'mansikka';  // 合法变量名;可以用中文
?>

变量默认总是传值赋值。那也就是说,当将一个表达式的值赋予一个变量时,整个原始表达式的值被赋值到目标变量。这意味着,例如,当一个变量的值赋予另外一个变量时,改变其中一个变量的值,将不会影响到另外一个变量。有关这种类型的赋值操作,请参阅表达式一章。

PHP 也提供了另外一种方式给变量赋值:引用赋值。这意味着新的变量简单的引用(换言之,“成为其别名” 或者 “指向”)了原始变量。改动新的变量将影响到原始变量,反之亦然。

使用引用赋值,简单地将一个 & 符号加到将要赋值的变量前(源变量)。例如,下列代码片断将输出“My name is Bob”两次:

<?php
$foo = 'Bob';              // 将 'Bob' 赋给 $foo
$bar = &$foo;              // 通过 $bar 引用 $foo
$bar = "My name is $bar";  // 修改 $bar 变量
echo $bar;
echo $foo;                 // $foo 的值也被修改
?>

有一点重要事项必须指出,那就是只有有名字的变量才可以引用赋值。

<?php
$foo = 25;
$bar = &$foo;      // 合法的赋值
$bar = &(24 * 7);  // 非法; 引用没有名字的表达式

function test()
{
  return 25;
}

$bar = &test();    // 非法
?>

虽然在 PHP 中并不需要初始化变量,但对变量进行初始化是个好习惯。未初始化的变量具有其类型的默认值 - 布尔类型的变量默认值是 FALSE,整形和浮点型变量默认值是零,字符串型变量默认值是空字符串或者数组变量的默认值是空数组。

Example #1 未初始化变量的默认值

<?php
// Unset AND unreferenced (no use context) variable; outputs NULL
var_dump($unset_var);

// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool ? "true\n" : "false\n");

// String usage; outputs 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);

// Integer usage; outputs 'int(25)'
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);

// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);

// Array usage; outputs array(1) {  [3]=>  string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);

// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>

依赖未初始化变量的默认值在某些情况下会有问题,例如把一个文件包含到另一个之中时碰上相同的变量名。另外把 register_globals 打开是一个主要的安全隐患。使用未初始化的变量会发出E_NOTICE错误,但是在向一个未初始化的数组附加单元时不会。 isset() 语言结构可以用来检测一个变量是否已被初始化。

预定义变量

PHP 提供了大量的预定义变量。由于许多变量依赖于运行的服务器的版本和设置,及其它因素,所以并没有详细的说明文档。一些预定义变量在 PHP 以命令行形式运行时并不生效。有关这些变量的详细列表,请参阅预定义变量一章。

警告

PHP 4.2.0 以及后续版本中,PHP 指令 register_globals 的默认值为 off。这是 PHP 的一个主要变化。让 register_globals 的值为 off 将影响到预定义变量集在全局范围内的有效性。例如,为了得到 DOCUMENT_ROOT 的值,将必须使用 $_SERVER[‘DOCUMENT_ROOT’] 代替 $DOCUMENT_ROOT,又如,使用 $_GET[‘id’] 来代替 $id 从 URL http://www.example.com/test.php?id=3 中获取 id 值,亦或使用 $_ENV[‘HOME’] 来代替 $HOME 获取环境变量 HOME 的值。

更多相关信息,请阅读 register_globals 的配置项条目,安全一章中的使用 Register Globals,以及 PHP » 4.1.0 和 » 4.2.0 的发布公告。

如果有可用的 PHP 预定义变量那最好用,如超全局数组。

从 PHP 4.1.0 开始,PHP 提供了一套附加的预定数组,这些数组变量包含了来自 web 服务器(如果可用),运行环境,和用户输入的数据。这些数组非常特别,它们在全局范围内自动生效,例如,在任何范围内自动生效。因此通常被称为自动全局变量(autoglobals)或者超全局变量(superglobals)。(PHP 中没有用户自定义超全局变量的机制。)超全局变量罗列于下文中;但是为了得到它们的内容和关于 PHP 预定义变量的进一步的讨论以及它们的本质,请参阅预定义变量。而且,你也将注意到旧的预定义数组($HTTP_*_VARS)仍旧存在。自 PHP 5.0.0 起, 用 register_long_arrays 设置选项可禁用 长类型的 PHP 预定义变量数组。

注解

可变变量

超级全局变量不能被用作可变变量。

注解

尽管超全局变量和 HTTP_*_VARS 同时存在。但是他们并不是同一个变量,所以改变一个的值并不会对另一个产生影响。

如果某些 variables_order 中的变量没有设定,它们的对应的 PHP 预定义数组也是空的。

变量范围

变量的范围即它定义的上下文背景(也就是它的生效范围)。大部分的 PHP 变量只有一个单独的范围。这个单独的范围跨度同样包含了 include 和 require 引入的文件。例如:

<?php
 $a = 1;
 include 'b.inc';
?>

这里变量 $a 将会在包含文件 b.inc 中生效。但是,在用户自定义函数中,一个局部函数范围将被引入。任何用于函数内部的变量按缺省情况将被限制在局部函数范围内。例如:

<?php
 $a = 1; /* global scope */

 function Test()
 {
   echo $a; /* reference to local scope variable */
 }

 Test();
?>

这个脚本不会有任何输出,因为 echo 语句引用了一个局部版本的变量 $a,而且在这个范围内,它并没有被赋值。你可能注意到 PHP 的全局变量和 C 语言有一点点不同,在 C 语言中,全局变量在函数中自动生效,除非被局部变量覆盖。这可能引起一些问题,有些人可能不小心就改变了一个全局变量。PHP 中全局变量在函数中使用时必须申明为global。

global 关键字

首先,一个使用 global 的例子:

Example #1 使用 global

<?php
  $a = 1;
  $b = 2;

  function Sum()
  {
     global $a, $b;

     $b = $a + $b;
  }

  Sum();
  echo $b;
?>

以上脚本的输出将是“3”。在函数中申明了全局变量 $a 和 $b,任何变量的所有引用变量都会指向到全局变量。对于一个函数能够申明的全局变量的最大个数,PHP 没有限制。

在全局范围内访问变量的第二个办法,是用特殊的 PHP 自定义 $GLOBALS 数组。前面的例子可以写成:

Example #2 使用 $GLOBALS 替代 global

<?php
$a = 1;
$b = 2;

function Sum()
{
   $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Sum();
echo $b;
?>

$GLOBALS 是一个关联数组,每一个变量为一个元素,键名对应变量名,值对应变量的内容。$GLOBALS 之所以在全局范围内存在,是因为 $GLOBALS 是一个超全局变量。以下范例显示了超全局变量的用处:

Example #3 演示超全局变量和作用域的例子

<?php
function test_global()
{
   // 大多数的预定义变量并不 "super",它们需要用 'global' 关键字来使它们在函数的本地区域中有效。
   global $HTTP_POST_VARS;

   echo $HTTP_POST_VARS['name'];

   // Superglobals 在任何范围内都有效,它们并不需要 'global' 声明。Superglobals 是在 PHP 4.1.0 引入的。
   echo $_POST['name'];
}
?>
使用静态变量

变量范围的另一个重要特性是静态变量(static variable)。静态变量仅在局部函数域中存在,但当程序执行离开此作用域时,其值并不丢失。看看下面的例子:

Example #4 演示需要静态变量的例子

<?php
function Test()
{
   $a = 0;
   echo $a;
   $a++;
}
?>

本函数没什么用处,因为每次调用时都会将 $a 的值设为 0 并输出 “0”。将变量加一的 $a++ 没有作用,因为一旦退出本函数则变量 $a 就不存在了。要写一个不会丢失本次计数值的计数函数,要将变量 $a 定义为静态的:

Example #5 使用静态变量的例子

<?php
function test()
{
   static $a = 0;
   echo $a;
   $a++;
}
?>

现在,变量$a在第一调用test()时被初始化,每次调用 test() 函数都会输出 $a 的值并加一。

静态变量也提供了一种处理递归函数的方法。递归函数是一种调用自己的函数。写递归函数时要小心,因为可能会无穷递归下去。必须确保有充分的方法来中止递归。一下这个简单的函数递归计数到 10,使用静态变量 $count 来判断何时停止:

Example #6 静态变量与递归函数

<?php
function test()
{
   static $count = 0;

   $count++;
   echo $count;
   if ($count < 10) {
       test();
   }
   $count--;
}
?>

Example #7 声明静态变量

<?php
function foo(){
   static $int = 0;          // correct
   static $int = 1+2;        // wrong  (as it is an expression)
   static $int = sqrt(121);  // wrong  (as it is an expression too)

   $int++;
   echo $int;
}
?>
全局和静态变量的引用

在 Zend 引擎 1 代,它驱动了 PHP4,对于变量的 static 和 global 定义是以 references 的方式实现的。例如,在一个函数域内部用 global 语句导入的一个真正的全局变量实际上是建立了一个到全局变量的引用。这有可能导致预料之外的行为,如以下例子所演示的:

<?php
function test_global_ref() {
   global $obj;
   $obj = &new stdclass;
}

function test_global_noref() {
   global $obj;
   $obj = new stdclass;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

以上例程会输出:

NULL
object(stdClass)(0) {
}

类似的行为也适用于 static 语句。引用并不是静态地存储的:

<?php
function &get_instance_ref() {
   static $obj;

   echo 'Static object: ';
   var_dump($obj);
   if (!isset($obj)) {
       // 将一个引用赋值给静态变量
       $obj = &new stdclass;
   }
   $obj->property++;
   return $obj;
}

function &get_instance_noref() {
   static $obj;

   echo 'Static object: ';
   var_dump($obj);
   if (!isset($obj)) {
       // 将一个对象赋值给静态变量
       $obj = new stdclass;
   }
   $obj->property++;
   return $obj;
}

$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>

以上例程会输出:

Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}

上例演示了当把一个引用赋值给一个静态变量时,第二次调用 &get_instance_ref() 函数时其值并没有被记住。

可变变量

有时候使用可变变量名是很方便的。就是说,一个变量的变量名可以动态的设置和使用。一个普通的变量通过声明来设置,例如:

<?php
$a = 'hello';
?>

一个可变变量获取了一个普通变量的值作为这个可变变量的变量名。在上面的例子中 hello 使用了两个美元符号($)以后,就可以作为一个可变变量的变量了。例如:

<?php
$$a = 'world';
?>

这时,两个变量都被定义了:$a 的内容是“hello”并且 $hello 的内容是“world”。因此,可以表述为:

<?php
echo "$a ${$a}";
?>

以下写法更准确并且会输出同样的结果:

<?php
echo "$a $hello";
?>

它们都会输出:hello world。

要将可变变量用于数组,必须解决一个模棱两可的问题。这就是当写下 $$a[1] 时,解析器需要知道是想要 $a[1] 作为一个变量呢,还是想要 $$a 作为一个变量并取出该变量中索引为 [1] 的值。解决此问题的语法是,对第一种情况用 ${$a[1]},对第二种情况用 ${$a}[1]。

警告

注意,在 PHP 的函数和类的方法中,超全局变量不能用作可变变量。

来自 PHP 之外的变量

HTML 表单(GET 和 POST)

当一个表单体交给 PHP 脚本时,表单中的信息会自动在脚本中可用。有很多方法访问此信息,例如:

Example #1 一个简单的 HTML 表单

<form action="foo.php" method="POST">
   Name:  <input type="text" name="username"><br />
   Email: <input type="text" name="email"><br />
   <input type="submit" name="submit" value="Submit me!" />
</form>

根据特定的设置和个人的喜好,有很多种方法访问 HTML 表单中的数据。例如:

Example #2 从一个简单的 POST HTML 表单访问数据

<?php
// 自 PHP 4.1.0 起可用
  echo $_POST['username'];
  echo $_REQUEST['username'];

  import_request_variables('p', 'p_');
  echo $p_username;
// PHP 6以后将无效。自 PHP 5.0.0 起,这些较长的预定义变量
// 可用 register_long_arrays 指令关闭。

  echo $HTTP_POST_VARS['username'];

// 如果 PHP 指令 register_globals = on 时可用。不过自
// PHP 4.2.0 起默认值为 register_globals = off。
// 不提倡使用/依赖此种方法。

   echo $username;
?>

使用 GET 表单也类似,只不过要用适当的 GET 预定义变量。GET 也适用于 QUERY_STRING(URL 中在“?”之后的信息)。因此,举例说,http://www.example.com/test.php?id=3 包含有可用 $_GET[‘id’] 访问的 GET 数据。参见 $_REQUEST 和 import_request_variables()。

注解

超全局数组和 $_POST 以及 $_GET 一样,自 PHP 4.1.0 起可用。

如上所示,在 PHP 4.2.0 之前 register_globals 的默认值是 on。PHP 社区鼓励大家不要依赖此指令,建议在编码时假定其为 off。

注解

magic_quotes_gpc 配置指令影响到 Get,Post 和 Cookie 的值。如果打开,值 (It’s “PHP!”) 会自动转换成 (It’s “PHP!”)。数据库的插入就需要转义。参见 addslashes(), stripslashes() 和 magic_quotes_sybase。

PHP 也懂得表单变量上下文中的数组(参见相关常见问题)。例如可以将相关的变量编成组,或者用此特性从多选输入框中取得值。例如,将一个表单 POST 给自己并在提交时显示数据:

Example #3 更复杂的表单变量

<?php
if (isset($_POST['action']) && $_POST['action'] == 'submitted') {
   echo '<pre>';

   print_r($_POST);
   echo '<a href="'. $_SERVER['PHP_SELF'] .'">Please try again</a>';

   echo '</pre>';
} else {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
   Name:  <input type="text" name="personal[name]"><br />
   Email: <input type="text" name="personal[email]"><br />
   Beer: <br>
   <select multiple name="beer[]">
       <option value="warthog">Warthog</option>
       <option value="guinness">Guinness</option>
       <option value="stuttgarter">Stuttgarter Schwabenbr</option>
   </select><br />
   <input type="hidden" name="action" value="submitted" />
   <input type="submit" name="submit" value="submit me!" />
</form>
<?php
}
?>
IMAGE SUBMIT 变量名

当提交表单时,可以用一幅图像代替标准的提交按钮,用类似这样的标记:

<input type="image" src="image.gif" name="sub" />

当用户点击到图像中的某处时,相应的表单会被传送到服务器,并加上两个变量 sub_x 和 sub_y。它们包含了用户点击图像的坐标。有经验的用户可能会注意到被浏览器发送的实际变量名包含的是一个点而不是下划线(即 sub.x 和 sub.y),但 PHP 自动将点转换成了下划线。

HTTP Cookies

PHP 透明地支持 » RFC 6265定义中的 HTTP cookies。Cookies 是一种在远端浏览器端存储数据并能追踪或识别再次访问的用户的机制。可以用 setcookie() 函数设定 cookies。Cookies 是 HTTP 信息头中的一部分,因此 SetCookie 函数必须在向浏览器发送任何输出之前调用。对于 header() 函数也有同样的限制。Cookie 数据会在相应的 cookie 数据数组中可用,例如 $_COOKIE,$HTTP_COOKIE_VARS 和 $_REQUEST。更多细节和例子见 setcookie() 手册页面。

如果要将多个值赋给一个 cookie 变量,必须将其赋成数组。例如:

<?php
 setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
 setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>

这将会建立两个单独的 cookie,尽管 MyCookie 在脚本中是一个单一的数组。如果想在仅仅一个 cookie 中设定多个值,考虑先在值上使用 serialize() 或 explode()。

注意在浏览器中一个 cookie 会替换掉上一个同名的 cookie,除非路径或者域不同。因此对于购物车程序可以保留一个计数器并一起传递,例如:

Example #4 一个 setcookie() 的示例

<?php
if (isset($_COOKIE['count'])) {
   $count = $_COOKIE['count'] + 1;
} else {
   $count = 1;
}
setcookie('count', $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>
变量名中的点

通常,PHP 不会改变传递给脚本中的变量名。然而应该注意到点(句号)不是 PHP 变量名中的合法字符。至于原因,看看:

<?php
$varname.ext;  /* 非法变量名 */
?>

这时,解析器看到是一个名为 $varname 的变量,后面跟着一个字符串连接运算符,后面跟着一个裸字符串(即没有加引号的字符串,且不匹配任何已知的健名或保留字)’ext’。很明显这不是想要的结果。 出于此原因,要注意 PHP 将会自动将变量名中的点替换成下划线。

确定变量类型

因为 PHP 会判断变量类型并在需要时进行转换(通常情况下),因此在某一时刻给定的变量是何种类型并不明显。PHP 包括几个函数可以判断变量的类型,例如: gettype(), is_array(), is_float(), is_int(), is_object() 和 is_string()。参见类型一章。

常量

语法

可以用 define() 函数来定义常量。在 PHP 5.3.0 以后,可以使用 const 关键字在类定义的外部定义常量。一个常量一旦被定义,就不能再改变或者取消定义。

常量只能包含标量数据(boolean,integer,float 和 string)。 可以定义 resource 常量,但应尽量避免,因为会造成不可预料的结果。

可以简单的通过指定其名字来取得常量的值,与变量不同,不应该在常量前面加上 $ 符号。如果常量名是动态的,也可以用函数 constant() 来获取常量的值。用 get_defined_constants() 可以获得所有已定义的常量列表。

php Note:: 常量和(全局)变量在不同的名字空间中。这意味着例如 TRUE 和 $TRUE 是不同的。

如果使用了一个未定义的常量,PHP 假定想要的是该常量本身的名字,如同用字符串调用它一样(CONSTANT 对应 “CONSTANT”)。此时将发出一个 E_NOTICE 级的错误。参见手册中为什么 $foo[bar] 是错误的(除非事先用 define() 将 bar 定义为一个常量)。如果只想检查是否定义了某常量,用 defined() 函数。

常量和变量有如下不同:

  • 常量前面没有美元符号($);
  • 常量只能用 define() 函数定义,而不能通过赋值语句;
  • 常量可以不用理会变量的作用域而在任何地方定义和访问;
  • 常量一旦定义就不能被重新定义或者取消定义;
  • 常量的值只能是标量。

Example #1 定义常量

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // 输出 "Constant" 并发出一个提示性信息
?>

Example #2 使用关键字 const 定义常量

<?php
// 以下代码在 PHP 5.3.0 后可以正常工作
const CONSTANT = 'Hello World';

echo CONSTANT;
?>

参见

常量

魔术常量

PHP 向它运行的任何脚本提供了大量的预定义常量。不过很多常量都是由不同的扩展库定义的,只有在加载了这些扩展库时才会出现,或者动态加载后,或者在编译时已经包括进去了。

有七个魔术常量它们的值随着它们在代码中的位置改变而改变。例如 __LINE__ 的值就依赖于它在脚本中所处的行来决定。这些特殊的常量不区分大小写,如下:

几个 PHP 的“魔术常量”

名称 说明
__LINE__ 文件中的当前行号。
__FILE__ 文件的完整路径和文件名。如果用在被包含文件中,则返回被包含的文件名。自 PHP 4.0.2 起,__FILE__ 总是包含一个绝对路径(如果是符号连接,则是解析后的绝对路径),而在此之前的版本有时会包含一个相对路径。
__DIR__ 文件所在的目录。如果用在被包括文件中,则返回被包括的文件所在的目录。它等价于 dirname(__FILE__)。除非是根目录,否则目录中名不包括末尾的斜杠。(PHP 5.3.0中新增) =
__FUNCTION__ 函数名称(PHP 4.3.0 新加)。自 PHP 5 起本常量返回该函数被定义时的名字(区分大小写)。在 PHP 4 中该值总是小写字母的。
__CLASS__ 类的名称(PHP 4.3.0 新加)。自 PHP 5 起本常量返回该类被定义时的名字(区分大小写)。在 PHP 4 中该值总是小写字母的。
__METHOD__ 类的方法名(PHP 5.0.0 新加)。返回该方法被定义时的名字(区分大小写)。
__NAMESPACE__ 当前命名空间的名称(大小写敏感)。这个常量是在编译时定义的(PHP 5.3.0 新增)

参见

get_class(), get_object_vars(), file_exists() 和 function_exists()。

常量是一个简单值的标识符(名字)。如同其名称所暗示的,在脚本执行期间该值不能改变(除了所谓的魔术常量,它们其实不是常量)。常量默认为大小写敏感。通常常量标识符总是大写的。

常量名和其它任何 PHP 标签遵循同样的命名规则。合法的常量名以字母或下划线开始,后面跟着任何字母,数字或下划线。用正则表达式是这样表达的:

[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Tip

参见

Userland Naming Guide。

Example #1 合法与非法的常量名

<?php

// 合法的常量名
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more");

// 非法的常量名
define("2FOO",    "something");

// 下面的定义是合法的,但应该避免这样做:(自定义常量不要以__开头)
// 也许将来有一天PHP会定义一个__FOO__的魔术常量
// 这样就会与你的代码相冲突
define("__FOO__", "something");

?>

php Note:: 在这里,字母是 a-z,A-Z,以及从 127 到 255(0x7f-0xff)的 ASCII 字符。

和 superglobals 一样,常量的范围是全局的。不用管作用域就可以在脚本的任何地方访问常量。有关作用得更多信息请阅读手册中的变量范围。

表达式

表达式是 PHP 最重要的基石。在 PHP 中,几乎所写的任何东西都是一个表达式。简单但却最精确的定义一个表达式的方式就是“任何有值的东西”。

最基本的表达式形式是常量和变量。当键入“$a = 5”,即将值“5”分配给变量 $a。“5”,很明显,其值为 5,换句话说“5”是一个值为 5 的表达式(在这里,“5”是一个整型常量)。

赋值之后,所期待情况是 $a 的值为 5,因而如果写下 $b = $a,期望的是它犹如 $b = 5 一样。换句话说,$a 是一个值也为 5 的表达式。如果一切运行正确,那这正是将要发生的正确结果。

稍微复杂的表达式例子就是函数。例如,考虑下面的函数:

<?php
function foo ()
{
   return 5;
}
?>

假定已经熟悉了函数的概念(如果不是的话,请看一下函数的相关章节),那么键入 $c = foo() 从本质上来说就如写下 $c = 5,这没错。函数也是表达式,表达式的值即为它们的返回值。既然 foo() 返回 5,表达式“foo()”的值也是 5。通常函数不会仅仅返回一个静态值,而可能会计算一些东西。

当然,PHP 中的值常常并非是整型的。PHP 支持四种标量值(标量值不能拆分为更小的单元,例如和数组不同)类型:整型值(integer),浮点数值(float),字符串值(string)和布尔值(boolean)。PHP 也支持两种复合类型:数组和对象。这两种类型具可以赋值给变量或者从函数返回。

PHP 和其它语言一样在表达式的道路上发展,但推进得更深远。PHP 是一种面向表达式的语言,从这一方面来讲几乎一切都是表达式。考虑刚才已经研究过的例子,“$a = 5”。很显然这里涉及到两个值,整型常量 5 的值以及而且变量 $a 的值,它也被更新为 5。但是事实是这里还涉及到一个额外的值,即附值语句本身的值。赋值语句本身求值为被赋的值,即 5。实际上这意味着“$a = 5”,不必管它是做什么的,是一个值为 5 的表达式。因而,这样写“$b = ($a = 5)”和这样写“$a =5; $b=5”(分号标志着语句的结束)是一样的。因为赋值操作的顺序是由右到左的,也可以这么写“$b = $a =5”。

另外一个很好的面向表达式的例子就是前、后递增和递减。PHP 和多数其它语言的用户应该比较熟悉变量 ++ 和变量 – 符号。即递增和递减运算符。在 PHP/FI 2 中,语句“$a++”没有值(不是表达式),这样的话你便不能为其赋值或者以任何其它方式来使用它。PHP 通过将其变为了表达式,类似 C 语言,增强了递增/递减的能力。在 PHP 和 C 语言 中,有两种类型的递增前递增和后递增,本质上来讲,前递增和后递增均增加了变量的值,并且对于变量的影响是相同的。不同的是递增表达式的值。前递增,写做“++$variable”,求增加后的值(PHP 在读取变量的值之前,增加变量的值,因而称之为“前递增”)。后递增,写做“$variable++”,求变量未递增之前的原始值(PHP 在读取变量的值之后,增加变量的值,因而叫做“后递增”)。

一个常用到表达式类型是比较表达式。这些表达式求值 FALSE 或 TRUE。PHP 支持 >(大于),>=(大于等于),==(等于),!=(不等于),<(小于),<= (小于等于)。PHP 还支持全等运算符 ===(值和类型均相同)和非全等运算符 !==(值或者类型不同)。这些表达式都是在条件判断语句,比如,if 语句中最常用的。

这里,将要研究的最后一个例子是组合的运算赋值表达式。已经知道如果想要为变量 $a 加1,可以简单的写“$a++”或者“++$a”。但是如果想为变量增加大于 1 的值,比如 3,该怎么做?可以多次写“$a++”,但这样明显不是一种高效舒适的方法,一个更加通用的做法是“$a = $a + 3”。“$a + 3”计算 $a 加上 3 的值,并且得到的值重新赋予变量 $a,于是 $a 的值增加了3。在 PHP 及其它几种类似 C 的语言中,可以以一种更加简短的形式完成上述功能,因而也更加清楚快捷。为 $a 的当前值加 3,可以这样写:“$a += 3”。这里的意思是“取变量 $a 的值,加 3,得到的结果再次分配给变量 $a”。除了更简略和清楚外,也可以更快的运行。“$a += 3”的值,如同一个正常赋值操作的值,是赋值后的值。注意它不是 3,而是 $a 的值加上3 之后的值(此值将被赋给 $a)。任何二元运算符都可以用运算赋值模式,例如“$a -= 5”(从变量 $a 的值中减去 5),“$b *= 7”(变量 $b 乘以 7),等等。

还有一个表达式,如果没有在别的语言中看到过的话,可能看上去很奇怪,即三元条件运算符:

<?php $first ? $second : $third ?>

如果第一个子表达式的值是 TRUE(非零),那么计算第二个子表达式的值,其值即为整个表达式的值。否则,将是第三个子表达式的值。 下面的例子一般来说应该有助于理解前、后递增和表达式:

<?php
function double($i)
{
   return $i*2;
}
$b = $a = 5;        /* assign the value five into the variable $a and $b */
$c = $a++;          /* post-increment, assign original value of $a
                      (5) to $c */
$e = $d = ++$b;     /* pre-increment, assign the incremented value of
                      $b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f = double($d++);  /* assign twice the value of $d before
                      the increment, 2*6 = 12 to $f */
$g = double(++$e);  /* assign twice the value of $e after
                      the increment, 2*7 = 14 to $g */
$h = $g += 10;      /* first, $g is incremented by 10 and ends with the
                      value of 24. the value of the assignment (24) is
                      then assigned into $h, and $h ends with the value
                      of 24 as well. */
?>

一些表达式可以被当成语句。这时,一条语句的形式是 ‘expr’ ‘;’,即一个表达式加一个分号结尾。在“$b=$a=5;”中,$a=5 是一个有效的表达式,但它本身不是一条语句。“$b=$a=5;”是一条有效的语句。

最后一件值得提起的事情就是表达式的真值。在许多事件中,大体上主要是在条件执行和循环中,不要专注于表达式中明确的值,反而要注意表达式的值是否是 TRUE 或者 FALSE。常量 TRUE 和 FALSE(大小写无关)是两种可能的 Boolean 值。如果有必要,一个表达式将自动转换为 Boolean。参见类型强制转换一节。

PHP 提供了一套完整强大的表达式,而为它提供完整的文件资料已经超出了本手册的范围。上面的例子应该为你提供了一个好的关于什么是表达式和怎样构建一个有用的表达式的概念。在本手册的其余部分,我们将始终使用 expr 来表示一个有效的 PHP 表达式。

运算符

运算符优先级

运算符优先级指定了两个表达式绑定得有多“紧密”。例如,表达式 1 + 5 * 3 的结果是 16 而不是 18 是因为乘号(“*”)的优先级比加号(“+”)高。必要时可以用括号来强制改变优先级。例如:(1 + 5) * 3 的值为 18。如果运算符优先级相同,则使用从左到右的左联顺序。

下表从高到低列出了运算符的优先级。同一行中的运算符具有相同优先级,此时它们的结合方向决定求值顺序。

运算符优先级 结合方向 运算符 附加信息 非结合 clone new clone 和 new 左 [ array() 非结合 ++ – 递增/递减运算符 非结合 ~ - (int) (float) (string) (array) (object) (bool) @ 类型 非结合 instanceof 类型 右结合 ! 逻辑操作符 左 * / % 算术运算符 左 + - . 算术运算符 和 字符串运算符 左 << >> 位运算符 非结合 < <= > >= <> 比较运算符 非结合 == != === !== 比较运算符 左 & 位运算符 和 引用 左 ^ 位运算符 左 | 位运算符 左 && 逻辑运算符 左 || 逻辑运算符 左 ? : 三元运算符 右 = += -= *= /= .= %= &= |= ^= <<= >>= 赋值运算符 左 and 逻辑运算符 左 xor 逻辑运算符 左 or 逻辑运算符 左 , 多处用到 左联表示表达式从左向右求值,右联相反。

Example #1 结合方向 <?php $a = 3 * 3 % 5; // (3 * 3) % 5 = 4 $a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$a = 1; $b = 2; $a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5 ?> 使用括号可以增强代码的可读性。 Note:

尽管 = 比其它大多数的运算符的优先级低,PHP 仍旧允许类似如下的表达式:if (!$a = foo()),在此例中 foo() 的返回值被赋给了 $a。

算术运算符

还记得学校里学到的基本数学知识吗?就和它们一样。

算术运算符 例子 名称 结果 -$a 取反 $a 的负值。 $a + $b 加法 $a 和 $b 的和。 $a - $b 减法 $a 和 $b 的差。 $a * $b 乘法 $a 和 $b 的积。 $a / $b 除法 $a 除以 $b 的商。 $a % $b 取模 $a 除以 $b 的余数。 除法运算符总是返回浮点数。只有在下列情况例外:两个操作数都是整数(或字符串转换成的整数)并且正好能整除,这时它返回一个整数。

取模运算符的操作数在运算之前都会转换成整数(除去小数部分)。

Note: 取模 $a % $b 在 $a 为负值时的结果也是负值。

参见手册中的数学函数。

赋值运算符

基本的赋值运算符是“=”。一开始可能会以为它是“等于”,其实不是的。它实际上意味着把右边表达式的值赋给左边的运算数。

赋值运算表达式的值也就是所赋的值。也就是说,“$a = 3”的值是 3。这样就可以做一些小技巧:

<?php

$a = ($b = 4) + 5; // $a 现在成了 9,而 $b 成了 4。

?> 在基本赋值运算符之外,还有适合于所有二元算术,数组集合和字符串运算符的“组合运算符”,这样可以在一个表达式中使用它的值并把表达式的结果赋给它,例如:

<?php

$a = 3; $a += 5; // sets $a to 8, as if we had said: $a = $a + 5; $b = “Hello ”; $b .= “There!”; // sets $b to “Hello There!”, just like $b = $b . “There!”;

?> 注意赋值运算将原变量的值拷贝到新变量中(传值赋值),所以改变其中一个并不影响另一个。这也适合于在很密集的循环中拷贝一些值例如大数组。也可以使用引用赋值,用 $var = &$othervar; 语法。引用赋值意味着两个变量都指向同一个数据,没有任何数据的拷贝。有关引用的更多信息见引用的说明。在 PHP 5中,对象总是通过引用赋值的,除非明确使用新的 clone关键字。

位运算符

位运算符允许对整型数中指定的位进行置位。如果左右参数都是字符串,则位运算符将操作字符的 ASCII 值。

<?php echo 12 ^ 9; // 输出为 ‘5’

echo “12” ^ “9”; // 输出退格字符(ascii 8)
// (‘1’ (ascii 49)) ^ (‘9’ (ascii 57)) = #8
echo “hallo” ^ “hello”; // 输出 ascii 值 #0 #4 #0 #0 #0
// ‘a’ ^ ‘e’ = #4
echo 2 ^ “3”; // 输出 1
// 2 ^ ((int)”3”) == 1
echo “2” ^ 3; // 输出 1
// ((int)”2”) ^ 3 == 1

?> 位运算符 例子 名称 结果 $a & $b And(按位与) 将把 $a 和 $b 中都为 1 的位设为 1。 $a | $b Or(按位或) 将把 $a 或者 $b 中为 1 的位设为 1。 $a ^ $b Xor(按位异或) 将把 $a 和 $b 中不同的位设为 1。 ~ $a Not(按位非) 将 $a 中为 0 的位设为 1,反之亦然。 $a << $b Shift left(左移) 将 $a 中的位向左移动 $b 次(每一次移动都表示“乘以 2”)。 $a >> $b Shift right(右移) 将 $a 中的位向右移动 $b 次(每一次移动都表示“除以 2”)。 Example #1 Bit shifting on integers <?php /*

  • Here are the examples.

*/

echo “n— BIT SHIFT RIGHT ON POSITIVE INTEGERS —n”;

$val = 4; $places = 1; $res = $val >> $places; p($res, $val, ‘>>’, $places, ‘copy of sign bit shifted into left side’);

$val = 4; $places = 2; $res = $val >> $places; p($res, $val, ‘>>’, $places);

$val = 4; $places = 3; $res = $val >> $places; p($res, $val, ‘>>’, $places, ‘bits shift out right side’);

$val = 4; $places = 4; $res = $val >> $places; p($res, $val, ‘>>’, $places, ‘same result as above; can not shift beyond 0’);

echo “n— BIT SHIFT RIGHT ON NEGATIVE INTEGERS —n”;

$val = -4; $places = 1; $res = $val >> $places; p($res, $val, ‘>>’, $places, ‘copy of sign bit shifted into left side’);

$val = -4; $places = 2; $res = $val >> $places; p($res, $val, ‘>>’, $places, ‘bits shift out right side’);

$val = -4; $places = 3; $res = $val >> $places; p($res, $val, ‘>>’, $places, ‘same result as above; can not shift beyond -1’);

echo “n— BIT SHIFT LEFT ON POSITIVE INTEGERS —n”;

$val = 4; $places = 1; $res = $val << $places; p($res, $val, ‘<<’, $places, ‘zeros fill in right side’);

$val = 4; $places = (PHP_INT_SIZE * 8) - 4; $res = $val << $places; p($res, $val, ‘<<’, $places);

$val = 4; $places = (PHP_INT_SIZE * 8) - 3; $res = $val << $places; p($res, $val, ‘<<’, $places, ‘sign bits get shifted out’);

$val = 4; $places = (PHP_INT_SIZE * 8) - 2; $res = $val << $places; p($res, $val, ‘<<’, $places, ‘bits shift out left side’);

echo “n— BIT SHIFT LEFT ON NEGATIVE INTEGERS —n”;

$val = -4; $places = 1; $res = $val << $places; p($res, $val, ‘<<’, $places, ‘zeros fill in right side’);

$val = -4; $places = (PHP_INT_SIZE * 8) - 3; $res = $val << $places; p($res, $val, ‘<<’, $places);

$val = -4; $places = (PHP_INT_SIZE * 8) - 2; $res = $val << $places; p($res, $val, ‘<<’, $places, ‘bits shift out left side, including sign bit’);

/*
  • Ignore this bottom section,
  • it is just formatting to make output clearer.

*/

function p($res, $val, $op, $places, $note = ‘’) {

$format = ‘%0’ . (PHP_INT_SIZE * 8) . “bn”;

printf(“Expression: %d = %d %s %dn”, $res, $val, $op, $places);

echo ” Decimal:n”; printf(” val=%dn”, $val); printf(” res=%dn”, $res);

echo ” Binary:n”; printf(‘ val=’ . $format, $val); printf(‘ res=’ . $format, $res);

if ($note) {
echo ” NOTE: $noten”;

}

echo “n”;

} ?> 以上例程在 32 位机器上的输出:

— BIT SHIFT RIGHT ON POSITIVE INTEGERS — Expression: 2 = 4 >> 1

Decimal:
val=4 res=2
Binary:
val=00000000000000000000000000000100 res=00000000000000000000000000000010

NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
Decimal:
val=4 res=1
Binary:
val=00000000000000000000000000000100 res=00000000000000000000000000000001
Expression: 0 = 4 >> 3
Decimal:
val=4 res=0
Binary:
val=00000000000000000000000000000100 res=00000000000000000000000000000000

NOTE: bits shift out right side

Expression: 0 = 4 >> 4
Decimal:
val=4 res=0
Binary:
val=00000000000000000000000000000100 res=00000000000000000000000000000000

NOTE: same result as above; can not shift beyond 0

— BIT SHIFT RIGHT ON NEGATIVE INTEGERS — Expression: -2 = -4 >> 1

Decimal:
val=-4 res=-2
Binary:
val=11111111111111111111111111111100 res=11111111111111111111111111111110

NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
Decimal:
val=-4 res=-1
Binary:
val=11111111111111111111111111111100 res=11111111111111111111111111111111

NOTE: bits shift out right side

Expression: -1 = -4 >> 3
Decimal:
val=-4 res=-1
Binary:
val=11111111111111111111111111111100 res=11111111111111111111111111111111

NOTE: same result as above; can not shift beyond -1

— BIT SHIFT LEFT ON POSITIVE INTEGERS — Expression: 8 = 4 << 1

Decimal:
val=4 res=8
Binary:
val=00000000000000000000000000000100 res=00000000000000000000000000001000

NOTE: zeros fill in right side

Expression: 1073741824 = 4 << 28
Decimal:
val=4 res=1073741824
Binary:
val=00000000000000000000000000000100 res=01000000000000000000000000000000
Expression: -2147483648 = 4 << 29
Decimal:
val=4 res=-2147483648
Binary:
val=00000000000000000000000000000100 res=10000000000000000000000000000000

NOTE: sign bits get shifted out

Expression: 0 = 4 << 30
Decimal:
val=4 res=0
Binary:
val=00000000000000000000000000000100 res=00000000000000000000000000000000

NOTE: bits shift out left side

— BIT SHIFT LEFT ON NEGATIVE INTEGERS — Expression: -8 = -4 << 1

Decimal:
val=-4 res=-8
Binary:
val=11111111111111111111111111111100 res=11111111111111111111111111111000

NOTE: zeros fill in right side

Expression: -2147483648 = -4 << 29
Decimal:
val=-4 res=-2147483648
Binary:
val=11111111111111111111111111111100 res=10000000000000000000000000000000
Expression: 0 = -4 << 30
Decimal:
val=-4 res=0
Binary:
val=11111111111111111111111111111100 res=00000000000000000000000000000000

NOTE: bits shift out left side, including sign bit

以上例程在 64 位机器上的输出:

— BIT SHIFT RIGHT ON POSITIVE INTEGERS — Expression: 2 = 4 >> 1

Decimal:
val=4 res=2
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000010

NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
Decimal:
val=4 res=1
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000001
Expression: 0 = 4 >> 3
Decimal:
val=4 res=0
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000000

NOTE: bits shift out right side

Expression: 0 = 4 >> 4
Decimal:
val=4 res=0
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000000

NOTE: same result as above; can not shift beyond 0

— BIT SHIFT RIGHT ON NEGATIVE INTEGERS — Expression: -2 = -4 >> 1

Decimal:
val=-4 res=-2
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111110

NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
Decimal:
val=-4 res=-1
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111111

NOTE: bits shift out right side

Expression: -1 = -4 >> 3
Decimal:
val=-4 res=-1
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111111

NOTE: same result as above; can not shift beyond -1

— BIT SHIFT LEFT ON POSITIVE INTEGERS — Expression: 8 = 4 << 1

Decimal:
val=4 res=8
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000001000

NOTE: zeros fill in right side

Expression: 4611686018427387904 = 4 << 60
Decimal:
val=4 res=4611686018427387904
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100 res=0100000000000000000000000000000000000000000000000000000000000000
Expression: -9223372036854775808 = 4 << 61
Decimal:
val=4 res=-9223372036854775808
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100 res=1000000000000000000000000000000000000000000000000000000000000000

NOTE: sign bits get shifted out

Expression: 0 = 4 << 62
Decimal:
val=4 res=0
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000000

NOTE: bits shift out left side

— BIT SHIFT LEFT ON NEGATIVE INTEGERS — Expression: -8 = -4 << 1

Decimal:
val=-4 res=-8
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111000

NOTE: zeros fill in right side

Expression: -9223372036854775808 = -4 << 61
Decimal:
val=-4 res=-9223372036854775808
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100 res=1000000000000000000000000000000000000000000000000000000000000000
Expression: 0 = -4 << 62
Decimal:
val=-4 res=0
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100 res=0000000000000000000000000000000000000000000000000000000000000000

NOTE: bits shift out left side, including sign bit

Warning 在 32 位系统上不要右移超过 32 位。不要在结果可能超过 32 位的情况下左移。

比较运算符

比较运算符,如同它们名称所暗示的,允许对两个值进行比较。还可以参考 PHP 类型比较表看不同类型相互比较的例子。

比较运算符 例子 名称 结果 $a == $b 等于 TRUE,如果 $a 等于 $b。 $a === $b 全等 TRUE,如果 $a 等于 $b,并且它们的类型也相同。(PHP 4 引进) $a != $b 不等 TRUE,如果 $a 不等于 $b。 $a <> $b 不等 TRUE,如果 $a 不等于 $b。 $a !== $b 非全等 TRUE,如果 $a 不等于 $b,或者它们的类型不同。(PHP 4 引进) $a < $b 小与 TRUE,如果 $a 严格小于 $b。 $a > $b 大于 TRUE,如果 $a 严格 $b。 $a <= $b 小于等于 TRUE,如果 $a 小于或者等于 $b。 $a >= $b 大于等于 TRUE,如果 $a 大于或者等于 $b。 如果比较一个整数和字符串,则字符串会被转换为整数。如果比较两个数字字符串,则作为整数比较。此规则也适用于 switch 语句。

<?php var_dump(0 == “a”); // 0 == 0 -> true var_dump(“1” == “01”); // 1 == 1 -> true var_dump(“1” == “1e0”); // 1 == 1 -> true switch (“a”) { case 0:

echo “0”; break;
case “a”: // never reached because “a” is already matched with 0
echo “a”; break;

} ?> 对于多种类型,比较运算符根据下表比较(按顺序)。

比较多种类型 运算数 1 类型 运算数 1 类型 结果 null 或 string string 将 NULL 转换为 “”,进行数字或词汇比较 bool 或 null 任何其它类型 转换为 bool,FALSE < TRUE object object 内置类可以定义自己的比较,不同类不能比较,相同类和数组同样方式比较属性(PHP 4 中),PHP 5 有其自己的说明 string,resource 或 number string,resource 或 number 将字符串和资源转换成数字,按普通数学比较 array array 具有较少成员的数组较小,如果运算数 1 中的键不存在于运算数 2 中则数组无法比较,否则挨个值比较(见下例) array 任何其它类型 array 总是更大 object 任何其它类型 object 总是更大 Example #1 标准数组比较代码 <?php // 数组是用标准比较运算符这样比较的 function standard_array_compare($op1, $op2) {

if (count($op1) < count($op2)) {
return -1; // $op1 < $op2
} elseif (count($op1) > count($op2)) {
return 1; // $op1 > $op2

} foreach ($op1 as $key => $val) {

if (!array_key_exists($key, $op2)) {
return null; // uncomparable
} elseif ($val < $op2[$key]) {
return -1;
} elseif ($val > $op2[$key]) {
return 1;

}

} return 0; // $op1 == $op2

} ?> 参见 strcasecmp(), strcmp(),数组运算符和类型一章。

三元运算符

另一个条件运算符是“?:”(或三元)运算符 。

Example #2 赋默认值 <?php

// Example usage for: Ternary Operator $action = (empty($_POST[‘action’])) ? ‘default’ : $_POST[‘action’];

// The above is identical to this if/else statement if (empty($_POST[‘action’])) {

$action = ‘default’;
} else {
$action = $_POST[‘action’];

}

?>

表达式 (expr1) ? (expr2) : (expr3) 在 expr1 求值为 TRUE 时的值为 expr2,在 expr1 求值为 FALSE 时的值为 expr3。 Note: 注意三元运算符是个语句,因此其求值不是变量,而是语句的结果。如果想通过引用返回一个变量这点就很重要。在一个通过引用返回的函数中语句 return $var == 42 ? $a : $b; 将不起作用,以后的 PHP 版本会为此发出一条警告。

Note:

建议避免将三元运算符堆积在一起使用。当在一条语句中使用多个三元运算符时会造成 PHP 运算结果不清晰: Is is recommended that you avoid “stacking” ternary expressions. PHP’s behaviour when using more than one ternary operator within a single statement is non-obvious:

Example #3 不清晰的三元运算符行为 <?php // 乍看起来下面的输出是 ‘true’ echo (true?’true’:false?’t’:’f’);

// 然而,上面语句的实际输出是’t’,因为三元运算符是从左往右计算的

// 下面是与上面等价的语句,但更清晰 echo ((true ? ‘true’ : ‘false’) ? ‘t’ : ‘f’);

// here, you can see that the first expression is evaluated to ‘true’, which // in turn evaluates to (bool)true, thus returning the true branch of the // second ternary expression. ?>

错误控制运算符

PHP 支持一个错误控制运算符:@。当将其放置在一个 PHP 表达式之前,该表达式可能产生的任何错误信息都被忽略掉。

如果激活了 track_errors 特性,表达式所产生的任何错误信息都被存放在变量 $php_errormsg 中。此变量在每次出错时都会被覆盖,所以如果想用它的话就要尽早检查。

<?php /* Intentional file error */ $my_file = @file (‘non_existent_file’) or

die (“Failed opening file: error was ‘$php_errormsg’”);

// this works for any expression, not just functions: $value = @$cache[$key]; // will not issue a notice if the index $key doesn’t exist.

?> Note: @ 运算符只对表达式有效。对新手来说一个简单的规则就是:如果能从某处得到值,就能在它前面加上 @ 运算符。例如,可以把它放在变量,函数和 include 调用,常量,等等之前。不能把它放在函数或类的定义之前,也不能用于条件结构例如 if 和 foreach 等。

参见 error_reporting() 及手册中错误处理及日志函数的有关章节。

Warning 目前的“@”错误控制运算符前缀甚至使导致脚本终止的严重错误的错误报告也失效。这意味着如果在某个不存在或类型错误的函数调用前用了“@”来抑制错误信息,那脚本会没有任何迹象显示原因而死在那里。

执行运算符

PHP 支持一个执行运算符:反引号(``)。注意这不是单引号!PHP 将尝试将反引号中的内容作为外壳命令来执行,并将其输出信息返回(例如,可以赋给一个变量而不是简单地丢弃到标准输出)。使用反引号运算符“`”的效果与函数 shell_exec() 相同。

<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>

参见函数 popen()、 proc_open() 及手册中程序执行函数和 PHP 的命令行模式的有关章节。

递增/递减运算符

PHP 支持 C 风格的前/后递增与递减运算符。

Note: 递增/递减运算符不影响布尔值。递减 NULL 值也没有效果,但是递增 NULL 的结果是 1。

递增/递减运算符 例子 名称 效果 ++$a 前加 $a 的值加一,然后返回 $a。 $a++ 后加 返回 $a,然后将 $a 的值加一。 –$a 前减 $a 的值减一, 然后返回 $a。 $a– 后减 返回 $a,然后将 $a 的值减一。 一个简单的示例脚本:

<?php echo “<h3>Postincrement</h3>”; $a = 5; echo “Should be 5: ” . $a++ . “<br />n”; echo “Should be 6: ” . $a . “<br />n”;

echo “<h3>Preincrement</h3>”; $a = 5; echo “Should be 6: ” . ++$a . “<br />n”; echo “Should be 6: ” . $a . “<br />n”;

echo “<h3>Postdecrement</h3>”; $a = 5; echo “Should be 5: ” . $a– . “<br />n”; echo “Should be 4: ” . $a . “<br />n”;

echo “<h3>Predecrement</h3>”; $a = 5; echo “Should be 4: ” . –$a . “<br />n”; echo “Should be 4: ” . $a . “<br />n”; ?> 在处理字符变量的算数运算时,PHP 沿袭了 Perl 的习惯,而非 C 的。例如,在 Perl 中 ‘Z’+1 将得到 ‘AA’,而在 C 中,’Z’+1 将得到 ‘[‘(ord(‘Z’) == 90,ord(‘[‘) == 91)。注意字符变量只能递增,不能递减,并且只支持纯字母(a-z 和 A-Z)。

Example #1 涉及字符变量的算数运算 <?php $i = ‘W’; for ($n=0; $n<6; $n++) {

echo ++$i . “n”;

} ?> 以上例程会输出: X Y Z AA AB AC 递增或递减布尔值没有效果。

逻辑运算符

逻辑运算符 例子 名称 结果 $a and $b And(逻辑与) TRUE,如果 $a 与 $b 都为 TRUE。 $a or $b Or(逻辑或) TRUE,如果 $a 或 $b 任一为 TRUE。 $a xor $b Xor(逻辑异或) TRUE,如果 $a 或 $b 任一为 TRUE,但不同时是。 ! $a Not(逻辑非) TRUE,如果 $a 不为 TRUE。 $a && $b And(逻辑与) TRUE,如果 $a 与 $b 都为 TRUE。 $a || $b Or(逻辑或) TRUE,如果 $a 或 $b 任一为 TRUE。 “与”和“或”有两种不同形式运算符的原因是它们运算的优先级不同(见运算符优先级)。

Example #1 逻辑运算符示例 <?php

// 下面的 foo() 不会被调用,因为它们被运算符“短路”了。 $a = (false && foo()); $b = (true || foo()); $c = (false and foo()); $d = (true or foo());

// “||” 的优先级比 “or” 高 $e = false || true; // $e 被赋值为 (false || true),结果为 true $f = false or true; // $f 被赋值为 false [Altair注:”=” 的优先级比 “or” 高] var_dump($e, $f);

// “&&” 的优先级比 “and” 高 $g = true && false; // $g 被赋值为 (true && false),结果为 false $h = true and false; // $h 被赋值为 true [Altair注:”=” 的优先级比 “and” 高] var_dump($g, $h); ?> 以上例程的输出类似于: bool(true) bool(false) bool(false) bool(true)

字符串运算符

有两个字符串运算符。第一个是连接运算符(“.”),它返回其左右参数连接后的字符串。第二个是连接赋值运算符(“.=”),它将右边参数附加到左边的参数后。更多信息见赋值运算符。

<?php $a = “Hello ”; $b = $a . “World!”; // now $b contains “Hello World!”

$a = “Hello ”; $a .= “World!”; // now $a contains “Hello World!” ?> 参见字符串类型和字符串函数章节。

数组运算符

数组运算符 例子 名称 结果 $a + $b 联合 $a 和 $b 的联合。 $a == $b 相等 如果 $a 和 $b 具有相同的键/值对则为 TRUE。 $a === $b 全等 如果 $a 和 $b 具有相同的键/值对并且顺序和类型都相同则为 TRUE。 $a != $b 不等 如果 $a 不等于 $b 则为 TRUE。 $a <> $b 不等 如果 $a 不等于 $b 则为 TRUE。 $a !== $b 不全等 如果 $a 不全等于 $b 则为 TRUE。 + 运算符把右边的数组元素(除去键值与左边的数组元素相同的那些元素)附加到左边的数组后面,但是重复的键值不会被覆盖。

<?php $a = array(“a” => “apple”, “b” => “banana”); $b = array(“a” => “pear”, “b” => “strawberry”, “c” => “cherry”);

$c = $a + $b; // Union of $a and $b echo “Union of $a and $b: n”; var_dump($c);

$c = $b + $a; // Union of $b and $a echo “Union of $b and $a: n”; var_dump($c); ?> 执行后,此脚本会显示: Union of $a and $b: array(3) {

[“a”]=> string(5) “apple” [“b”]=> string(6) “banana” [“c”]=> string(6) “cherry”

} Union of $b and $a: array(3) {

[“a”]=> string(4) “pear” [“b”]=> string(10) “strawberry” [“c”]=> string(6) “cherry”

} 数组中的单元如果具有相同的键名和值则比较时相等。

Example #1 比较数组 <?php $a = array(“apple”, “banana”); $b = array(1 => “banana”, “0” => “apple”);

var_dump($a == $b); // bool(true) var_dump($a === $b); // bool(false) ?> 参见数组类型和数组函数章节。

类型运算符

instanceof 用于确定一个 PHP 变量是否属于某一类 class 的实例:

Example #1 instanceof 使用示例 <?php class MyClass { }

class NotMyClass { } $a = new MyClass;

var_dump($a instanceof MyClass); var_dump($a instanceof NotMyClass); ?> 以上例程会输出: bool(true) bool(false) instanceof 也可用来确定一个变量是不是继承自某一父类的子类的实例: can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class:

Example #2 instanceof 与继承类示例 <?php class ParentClass { }

class MyClass extends ParentClass { }

$a = new MyClass;

var_dump($a instanceof MyClass); var_dump($a instanceof ParentClass); ?> 以上例程会输出: bool(true) bool(true) 检查一个对象 不是 某个类的实例,可以使用 逻辑运算符 not。

Example #3 使用instanceof检查对象 不是 某一类的实例 <?php class MyClass { }

$a = new MyClass; var_dump(!($a instanceof stdClass)); ?> 以上例程会输出: bool(true) 最后,instanceof也可用于确定一个变量是不是实现了某个接口的对象的实例:

Example #4 Using instanceof for class <?php interface MyInterface { }

class MyClass implements MyInterface { }

$a = new MyClass;

var_dump($a instanceof MyClass); var_dump($a instanceof MyInterface); ?> 以上例程会输出: bool(true) bool(true) 虽然 instanceof 通常直接与类名一起使用,但也可以使用对象或字符串变量:

Example #5 Using instanceof with other variables <?php interface MyInterface { }

class MyClass implements MyInterface { }

$a = new MyClass; $b = new MyClass; $c = ‘MyClass’; $d = ‘NotMyClass’;

var_dump($a instanceof $b); // $b is an object of class MyClass var_dump($a instanceof $c); // $c is a string ‘MyClass’ var_dump($a instanceof $d); // $d is a string ‘NotMyClass’ ?> 以上例程会输出: bool(true) bool(true) bool(false) 然而 instanceof 的使用还有一些陷阱必须了解。在 PHP 5.1.0之前,如果要检查的类名称不存在,instanceof 会调用 __autoload()。另外,如果该类没有被装载则会产生一个致命错误。可以通过使用动态类引用(dynamic class reference)或用一个包含类名的字符串变量来避开这种问题:

Example #6 避免 PHP 5.0 中 instanceof 引起的类名查找和致命错误问题 <?php $d = ‘NotMyClass’; var_dump($a instanceof $d); // no fatal error here ?> 以上例程会输出: bool(false) instanceof 运算符是 PHP 5 引进的。在此之前用 is_a(),但是 is_a() 已经过时了,最好用 instanceof。

参见 get_class() 和 is_a()。

控制结构

简介

if

else

elseif/else if

流程控制的替代语法

while

do-while

for

foreach

break

continue

switch

declare

return

require

include

require_once

include_once

goto

函数

用户自定义函数

函数的参数

返回值

可变函数

内部(内置)函数

匿名函数

类与对象

前言

基本概念

属性

类常量

自动加载对象

构造函数和析构函数

访问控制

对象继承

范围解析操作符(::)

Static关键字

抽象类

接口

Traits

重载

对象迭代

设计模式

魔术方法

Final关键字

对象复制

对象比较

类型约束

后期静态绑定

对象和引用

对象序列化

OOP 变更日志

命名空间

命名空间概述

定义命名空间

定义子命名空间

在同一个文件中定义多个命名空间

使用命名空间:基础

命名空间和动态语言特征

namespace关键字和__NAMESPACE__常量

使用命名空间:别名/导入

全局空间

使用命名空间:后备全局函数/常量

名称解析规则

FAQ: 你需要知道关于命名空间的事

异常处理

扩展 PHP 内置的异常处理类

用户可以用自定义的异常处理类来扩展 PHP 内置的异常处理类。以下的代码说明了在内置的异常处理类中,哪些属性和方法在子类中是可访问和可继承的。译者注:以下这段代码只为说明内置异常处理类的结构,它并不是一段有实际意义的可用代码。

Example #1 内置的异常处理类 <?php class Exception {

protected $message = ‘Unknown exception’; // 异常信息 protected $code = 0; // 用户自定义异常代码 protected $file; // 发生异常的文件名 protected $line; // 发生异常的代码行号

function __construct($message = null, $code = 0);

final function getMessage(); // 返回异常信息 final function getCode(); // 返回异常代码 final function getFile(); // 返回发生异常的文件名 final function getLine(); // 返回发生异常的代码行号 final function getTrace(); // backtrace() 数组 final function getTraceAsString(); // 已格成化成字符串的 getTrace() 信息

/* 可重载的方法 */ function __toString(); // 可输出的字符串

} ?> 如果使用自定义的类来扩展内置异常处理类,并且要重新定义构造函数的话,建议同时调用 parent::__construct() 来检查所有的变量是否已被赋值。当对象要输出字符串的时候,可以重载 __toString() 并自定义输出的样式。

Example #2 扩展 PHP 内置的异常处理类 <?php /**

  • 自定义一个异常处理类

*/

class MyException extends Exception {

// 重定义构造器使 message 变为必须被指定的属性 public function __construct($message, $code = 0) {

// 自定义的代码

// 确保所有变量都被正确赋值 parent::__construct($message, $code);

}

// 自定义字符串输出的样式 public function __toString() {

return __CLASS__ . ”: [{$this->code}]: {$this->message}n”;

}

public function customFunction() {
echo “A Custom function for this type of exceptionn”;

}

}

/**
  • 创建一个用于测试异常处理机制的类

*/

class TestException {

public $var;

const THROW_NONE = 0; const THROW_CUSTOM = 1; const THROW_DEFAULT = 2;

function __construct($avalue = self::THROW_NONE) {

switch ($avalue) {
case self::THROW_CUSTOM:
// 抛出自定义异常 throw new MyException(‘1 is an invalid parameter’, 5); break;
case self::THROW_DEFAULT:
// 抛出默认的异常 throw new Exception(‘2 isnt allowed as a parameter’, 6); break;
default:
// 没有异常的情况下,创建一个对象 $this->var = $avalue; break;

}

}

}

// 例子 1 try {

$o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) { // 捕获异常
echo “Caught my exceptionn”, $e; $e->customFunction();
} catch (Exception $e) { // 被忽略
echo “Caught Default Exceptionn”, $e;

}

// 执行后续代码 var_dump($o); echo “nn”;

// 例子 2 try {

$o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) { // 不能匹配异常的种类,被忽略
echo “Caught my exceptionn”, $e; $e->customFunction();
} catch (Exception $e) { // 捕获异常
echo “Caught Default Exceptionn”, $e;

}

// 执行后续代码 var_dump($o); echo “nn”;

// 例子 3 try {

$o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) { // 捕获异常
echo “Default Exception caughtn”, $e;

}

// 执行后续代码 var_dump($o); echo “nn”;

// 例子 4 try {

$o = new TestException();
} catch (Exception $e) { // 没有异常,被忽略
echo “Default Exception caughtn”, $e;

}

// 执行后续代码 var_dump($o); echo “nn”; ?>

PHP 5 添加了类似于其它语言的异常处理模块。在 PHP 代码中所产生的异常可被 throw 语句抛出并被 catch 语句捕获。需要进行异常处理的代码都必须放入 try 代码块内,以便捕获可能存在的异常。每一个 try 至少要有一个与之对应的 catch。使用多个 catch 可以捕获不同的类所产生的异常。当 try 代码块不再抛出异常或者找不到 catch 能匹配所抛出的异常时,PHP 代码就会在跳转到最后一个 catch 的后面继续执行。当然,PHP 允许在 catch 代码块内再次抛出(throw)异常。

当一个异常被抛出时,其后(译者注:指抛出异常时所在的代码块)的代码将不会继续执行,而 PHP 就会尝试查找第一个能与之匹配的 catch。如果一个异常没有被捕获,而且又没用使用 set_exception_handler() 作相应的处理的话,那么 PHP 将会产生一个严重的错误,并且输出 Uncaught Exception ... (未捕获异常)的提示信息。

Note:

PHP 内部函数主要使用错误报告, 只有现代面向对象的扩展才使用异常。但错误可以很容易的通过ErrorException转换为异常。

Tip PHP标准库 (SPL) 提供了许多内建的异常类。

Example #1 抛出一个异常 <![CDATA[ <?php function inverse($x) {

if (!$x) {
throw new Exception(‘Division by zero.’);

} else return 1/$x;

}

try {
echo inverse(5) . “n”; echo inverse(0) . “n”;
} catch (Exception $e) {
echo ‘Caught exception: ‘, $e->getMessage(), “n”;

}

// Continue execution echo ‘Hello World’; ?> 以上例程会输出: 0.2 Caught exception: Division by zero. Hello World Example #2 嵌套的异常 <?php

class MyException extends Exception { }

class Test {
public function testing() {
try {
try {
throw new MyException(‘foo!’);
} catch (MyException $e) {
/* rethrow it */ throw $e;

}

} catch (Exception $e) {
var_dump($e->getMessage());

}

}

}

$foo = new Test; $foo->testing();

?> 以上例程会输出: string(4) “foo!”

Generators

Generators overview

Generator syntax

Generator objects

Comparing generators with Iterator objects

引用的解释

引用是什么

引用做什么

引用不是什么

引用传递

引用返回

取消引用

引用定位

预定义变量

超全局变量 — 超全局变量是在全部作用域中始终可用的内置变量

$GLOBALS — 引用全局作用域中可用的全部变量

$_SERVER — 服务器和执行环境信息

$_GET — HTTP GET 变量

$_POST — HTTP POST 变量

$_FILES — HTTP 文件上传变量

$_REQUEST — HTTP Request 变量

$_SESSION — Session 变量

$_ENV — 环境变量

$php_errormsg — 前一个错误信息

$HTTP_RAW_POST_DATA — 原生POST数据

$http_response_header — HTTP 响应头

$argc — 传递给脚本的参数数目

$argv — 传递给脚本的参数数组

预定义异常

Exception

ErrorException

预定义接口

遍历 — Traversable(遍历)接口

迭代器 — Iterator(迭代器)接口

聚合式迭代器 — IteratorAggregate(聚合式迭代器)接口

数组式访问 — ArrayAccess(数组式访问)接口

序列化 — 序列化接口

Closure — The Closure class

上下文(Context)选项和参数

Socket context options — Socket context option listing

HTTP context options — HTTP context option listing

FTP context options — FTP context option listing

SSL context options — SSL context option listing

CURL context options — CURL context option listing

Phar context options — Phar context option listing

Context parameters — Context parameter listing

支持的协议和封装协议

file:// — 访问本地文件系统

http:// — 访问 HTTP(s) 网址

ftp:// — 访问 FTP(s) URLs

php:// — 访问各个输入/输出流(I/O streams)

zlib:// — 压缩流

data:// — 数据(RFC 2397)

glob:// — 查找匹配的文件路径模式

phar:// — PHP 归档

ssh2:// — Secure Shell 2

rar:// — RAR

ogg:// — 音频流

expect:// — 处理交互式的流

安全

简介

总则

以 CGI 模式安装时

可能受到的攻击

情形一:只运行公开的文件

情形二:使用 –enable-force-cgi-redirect 选项

情形三:设置 doc_root 或 user_dir

情形四:PHP 解释器放在 web 目录以外

以 Apache 模块安装时

文件系统安全

Null 字符问题

数据库安全

设计数据库

连接数据库

加密存储模型

SQL 注入

错误报告

使用 Register Globals

用户提交的数据

魔术引号

什么是魔术引号

为什么要用魔术引号

为什么不用魔术引号

关闭魔术引号

隐藏 PHP

保持更新

特点

用 PHP 进行 HTTP 认证

会话

处理 XForms

文件上传处理

file-upload.post-method POST 方法上传 file-upload.errors 错误信息说明 file-upload.common-pitfalls 常见缺陷 file-upload.multiple 上传多个文件 file-upload.put-method 对 PUT 方法的支持

使用远程文件

连接处理

数据库永久连接

安全模式

ini.sect.safe-mode 保安措施和安全模式 safe-mode.functions 被安全模式限制或屏蔽的函数

PHP 的命令行模式

commandline.webserver Built-in web server commandline.ini INI settings

垃圾回收机制

gc.refcounting-basics 引用计数基本知识 gc.collecting-cycles 回收周期(Collecting Cycles) gc.performance-considerations 性能方面考虑的因素

函数

影响 PHP 行为的扩展

APC — Alternative PHP Cache(可选PHP缓存)

intro.apc 简介 apc.setup 安装/配置 apc.constants 预定义常量 ref.apc APC 函数 class.apciterator APCIterator — The APCIterator class

APD — Advanced PHP debugger

intro.apd 简介 apd.setup 安装/配置 apd.constants 预定义常量 apd.examples 范例 ref.apd APD 函数

bcompiler — PHP 字节码编译器

intro.bcompiler 简介 bcompiler.setup 安装/配置 bcompiler.constants 预定义常量 ref.bcompiler bcompiler 函数

错误处理 — 错误处理和日志记录

intro.errorfunc 简介 errorfunc.setup 安装/配置 errorfunc.constants 预定义常量 errorfunc.examples 范例 ref.errorfunc 错误处理 函数

htscanner — htaccess-like support for all SAPIs

intro.htscanner 简介 htscanner.setup 安装/配置

inclued — Inclusion hierarchy viewer

intro.inclued 简介 inclued.setup 安装/配置 inclued.constants 预定义常量 inclued.examples 范例 ref.inclued inclued 函数

Memtrack

intro.memtrack 简介 memtrack.setup 安装/配置 memtrack.constants 预定义常量 memtrack.examples 范例

输出控制 — 输出缓冲控制

intro.outcontrol 简介 outcontrol.setup 安装/配置 outcontrol.constants 预定义常量 outcontrol.examples 范例 ref.outcontrol Output Control 函数

PHP 选项/信息 — PHP 选项和信息

intro.info 简介 info.setup 安装/配置 info.constants 预定义常量 ref.info PHP 选项/信息 函数

runkit

intro.runkit 简介 runkit.constants 预定义常量 runkit.setup 安装/配置 ref.runkit runkit 函数

scream — Break the silence operator

intro.scream 简介 scream.setup 安装/配置 scream.examples 范例

Weakref — Weak References

intro.weakref 简介 weakref.setup 安装/配置 class.weakref WeakRef — The WeakRef class class.weakmap WeakMap — The WeakMap class

WinCache — Windows Cache for PHP

intro.wincache 简介 wincache.setup 安装/配置 wincache.constants 预定义常量 ref.wincache WinCache 函数 wincache.win32build Building for Windows

Xhprof — 层次式性能分析器

intro.xhprof 简介 xhprof.setup 安装/配置 xhprof.constants 预定义常量 xhprof.examples 范例 ref.xhprof Xhprof 函数

音频格式操作

身份认证服务

日历和事件相关扩展

日历和事件相关扩展

简介

历法扩展集包括了一系列用于在不同历法间进行转换的函数,它是以Julian Day计数为中介或标准来进行的。Julian Day计数是以公元前的4713年的1月1日为起点的一种计数法。为了在不同历法间进行转换,你首先要转换成Julian Day计数,然后再转换为你所需要的历法。Julian Day计数和Julian历法是非常不同的!Julian Day计数的更多信息可以参考» http://www.hermetic.ch/cal_stud/jdn.htm,历法系统的更多信息可以参考» http://www.fourmilab.ch/documents/calendar/本页中的引用包括在相应的文章中。

安装/配置
需求

构建此扩展不需要其他扩展。

安装

要使用本类函数,需要在编译 PHP 时加上 –enable-calendar 。

PHP 的 Windows 版本已内建对此扩展的支持。不需要载入额外的扩展来使用这些函数。

运行时配置

此扩展没有在 php.ini 中定义配置指令。

资源类型

此扩展没有定义资源类型。

预定义常量

下列常量由此扩展定义,且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

CAL_GREGORIAN (integer) CAL_JULIAN (integer) CAL_JEWISH (integer) CAL_FRENCH (integer) CAL_NUM_CALS (integer) CAL_DOW_DAYNO (integer) CAL_DOW_SHORT (integer) CAL_DOW_LONG (integer) CAL_MONTH_GREGORIAN_SHORT (integer) CAL_MONTH_GREGORIAN_LONG (integer) CAL_MONTH_JULIAN_SHORT (integer) CAL_MONTH_JULIAN_LONG (integer) CAL_MONTH_JEWISH (integer) CAL_MONTH_FRENCH (integer) 以下常量自 PHP 4.3.0 起可用:

CAL_EASTER_DEFAULT (integer) CAL_EASTER_ROMAN (integer) CAL_EASTER_ALWAYS_GREGORIAN (integer) CAL_EASTER_ALWAYS_JULIAN (integer) 以下常量自 PHP 5.0.0 起可用:

CAL_JEWISH_ADD_ALAFIM_GERESH (integer) CAL_JEWISH_ADD_ALAFIM (integer) CAL_JEWISH_ADD_GERESHAYIM (integer)

Calendar 函数

cal_days_in_month — 返回某个历法中某年中某月的天数 cal_from_jd — 转换Julian Day计数到一个支持的历法。 cal_info — 返回选定历法的信息 cal_to_jd — 从一个支持的历法转变为Julian Day计数。 easter_date — 得到指定年份的复活节午夜时的Unix时间戳。 easter_days — 得到指定年份的3月21日到复活节之间的天数 FrenchToJD — 从一个French Republican历法的日期得到Julian Day计数。 GregorianToJD — 转变一个Gregorian历法日期到Julian Day计数 JDDayOfWeek — 返回星期的日期 JDMonthName — 返回月份的名称 JDToFrench — 转变一个Julian Day计数到French Republican历法的日期 JDToGregorian — 转变一个Julian Day计数为Gregorian历法日期 jdtojewish — 转换一个julian天数为Jewish历法的日期 JDToJulian — 转变一个Julian Day计数到Julian历法的日期 jdtounix — 转变Julian Day计数为一个Unix时间戳 JewishToJD — 转变一个Jewish历法的日期为一个Julian Day计数 JulianToJD — 转变一个Julian历法的日期为Julian Day计数 unixtojd — 转变Unix时间戳为Julian Day计数

Date/Time

简介

These functions allow you to get the date and time from the server where your PHP scripts are running. You can use these functions to format the date and time in many different ways.

The date and time information is internally stored as a 64-bit number so all conceivably useful dates (including negative years) are supported. The range is from about 292 billion years in the past to the same in the future.

Note: Please keep in mind that these functions are dependent on the locale settings of your server. Make sure to take daylight saving time (use e.g. $date = strtotime(‘+7 days’, $date) and not $date += 7*24*60*60) and leap years into consideration when working with these functions.

注解

The timezones referenced in this section can be found in the 所支持的时区列表.

安装/配置
需求

构建此扩展不需要其他扩展。

安装

使用这些函数不需要安装,它们是 PHP 核心的一部分。

注解

Getting the latest timezone database

The latest version of the timezone database can be installed via PECL’s » timezonedb.

注解

Experimental DateTime support in PHP 5.1.x

Although the DateTime class (and related functions) are enabled by default since PHP 5.2.0, it is possible to add experimental support into PHP 5.1.x by using the following flag before configure/compile: CFLAGS=-DEXPERIMENTAL_DATE_SUPPORT=1

运行时配置

这些函数的行为受 php.ini 中的设置影响。

日期/时间配置选项

名字 默认 可修改范围 更新日志
date.default_latitude “31.7667” PHP_INI_ALL 自 PHP 5.0.0 起可用
date.default_longitude “35.2333” PHP_INI_ALL 自 PHP 5.0.0 起可用
date.sunrise_zenith “90.83” PHP_INI_ALL 自 PHP 5.0.0 起可用
date.sunset_zenith “90.83” PHP_INI_ALL 自 PHP 5.0.0 起可用
date.timezone “” PHP_INI_ALL 自 PHP 5.0.0 起可用

有关 PHP_INI_* 样式的更多详情与定义,见 Where a configuration setting may be set。

这是配置指令的简短说明。

  • date.default_latitude float 默认纬度。
  • date.default_longitude float 默认经度。
  • date.sunrise_zenith float 默认日出天顶。
  • date.sunset_zenith float 默认日落天顶。
  • date.timezone string 在未设定 TZ 环境变量时用于所有日期/时间函数的默认时区。优先顺序在 date_default_timezone_get() 页面中有说明。 支持的时区可参见 所支持的时区列表。

注解

前四个配置选项目前仅用于 date_sunrise() 和 date_sunset()。

资源类型

此扩展没有定义资源类型。

预定义常量

The 时间常量 are defined since PHP 5.1.1 and they offer standard date representations, which can be used along with the date format functions (like date()).

Following constants exists since PHP 5.1.2 and specify a format returned by functions date_sunrise() and date_sunset().

constant SUNFUNCS_RET_TIMESTAMP

(integer) Timestamp

constant SUNFUNCS_RET_STRING

(integer) Hours:minutes (example: 08:02)

constant SUNFUNCS_RET_DOUBLE

(integer) Hours as floating point number (example 8.75)

DateTime 类
简介

表示日期和时间。

类摘要
class DateTime
时间日期类
constant ATOM

格式:Y-m-dTH:i:s(例: 2005-08-15T15:52:01+00:00)

constant COOKIE

格式:l, d-M-y H:i:s T(例: Monday, 15-Aug-05 15:52:01 UTC)

constant ISO8601

格式:Y-m-dTH:i:sO(例: 2005-08-15T15:52:01+0000)

constant RFC822

格式:D, d M y H:i:s O(例: Mon, 15 Aug 05 15:52:01 +0000)

constant RFC850

格式:l, d-M-y H:i:s T(例: Monday, 15-Aug-05 15:52:01 UTC)

constant RFC1036

格式:D, d M y H:i:s O(例: Mon, 15 Aug 05 15:52:01 +0000)

constant RFC1123

格式:D, d M Y H:i:s O(例: Mon, 15 Aug 2005 15:52:01 +0000)

constant RFC2822

格式:D, d M Y H:i:s O(Mon, 15 Aug 2005 15:52:01 +0000)

constant RFC3339

格式:Y-m-dTH:i:sP 同DATE_ATOM (自从 PHP 5.1.3)

constant RSS

格式:D, d M Y H:i:s O(Mon, 15 Aug 2005 15:52:01 +0000)

constant W3C

格式:Y-m-dTH:i:sP World Wide Web Consortium (例: 2005-08-15T15:52:01+00:00)

construct([$time[, $timezone]])
参数:
  • $now (string) – 日期时间字符串.
  • $timezone (DateTimeZone) – $time的DateTimeZone对象
返回:

新DateTime实例. 过程化风格在失败时返回 FALSE.

Exception:

Emits Exception in case of an error.

add([$object, ]$interval)
参数:
  • $object (DateTime) – 仅过程化风格:由 date_create() 返回的 DateTime 类型的对象。此函数会修改这个对象。
  • $interval (DateInterval) – DateInterval 对象
返回:

返回被修改的 DateTime 对象, 失败返回 FALSE.

createFromFormat($format, $time[, $timezone])
参数:
  • $format (string) –
  • $time (string) –
  • $timezone (DateTimeZone) –
返回:

新DateTime实例 或者在失败时返回 FALSE.

diff(DateTime $datetime2[, bool $absolute = false])
参数:
  • $datetime2 (DateTime) –
  • $absolute (bool) –
返回:

DateInterval对象,表示两个日期之间的差异 或者在失败时返回 FALSE.

format($format)
参数:
  • $format (string) –
getLastErrors(void)
getOffset(void)
getTimestamp(void)
getTimezone(void)
modify($modify)
参数:
  • $modify (string) –
__set_state($array)
参数:
  • $array (array) –
setDate($year, $month, $day)
参数:
  • $year (int) –
  • $month (int) –
  • $day (int) –
setISODate($year, $week[, $day])
参数:
  • $year (int) –
  • $week (int) –
  • $day (int) – 默认1
setTime($hour, $minute[, $second])
参数:
  • $hour (int) –
  • $minute (int) –
  • $second (int) – 默认0
setTimestamp($unixtimestamp)
参数:
  • $unixtimestamp (int) –
setTimezone($timezone)
参数:
sub($interval)
参数:
__wakeup(void)
更新日志
版本 说明
5.2.2 比较DateTime对象的比较操作符改为按预期工作。在此之前,所有的DateTime对象被认为是相等的 (使用 ==).
DateTimeZone类
class DateTimeZone
constant AFRICA

1

constant AMERICA

2

constant ANTARCTICA

4

constant ARCTIC

8

constant ASIA

16

constant ATLANTIC

32

constant AUSTRALIA

64

constant EUROPE

128

constant INDIAN

256

constant PACIFIC

512

constant UTC

1024

constant ALL

2047

constant ALL_WITH_BC

4095

constant PER_COUNTRY

4096

__construct(string $timezone)
getLocation(void)
getName(void)
getOffset(DateTime $datetime)
getTransitions([int $timestamp_begin[, int $timestamp_end]])
listAbbreviations(void)
listIdentifiers([int $what = DateTimeZone::ALL[, string $country = NULL]])
DateInterval 类
class DateInterval
constant $y
constant $m
constant $d
constant $h
constant $i
constant $s
constant $invert
constant $days
__construct(string $interval_spec)
createFromDateString(string $time)
format(string $format)
DatePeriod 类
class DatePeriod
constant EXCLUDE_START_DATE

1

__construct(DateTime $start, DateInterval $interval, int $recurrences[, int $options])
__construct(DateTime $start, DateInterval $interval, DateTime $end[, int $options])
__construct(string $isostr[, int $options])
Date/Time 函数
checkdate

验证一个格里高里日期

PHP4,5 新版功能.

checkdate($month, $day, $year)
检查由参数构成的日期的合法性。如果每个参数都正确定义了则会被认为是有效的。
参数:
  • $month (int) – month 的值是从 1 到 12
  • $day (int) – Day 的值在给定的 month 所应该具有的天数范围之内,闰年已经考虑进去了
  • $year (int) – year 的值是从 1 到 32767
返回:

如果给出的日期有效则返回 TRUE,否则返回 FALSE

例 #1 checkdate() 例子:

var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));

以上例程会输出:

bool(true)
bool(false)
date_default_timezone_get

5.1.0 新版功能.

date_default_timezone_get()
— 取得一个脚本中所有日期时间函数所使用的默认时区
返回:返回一个 string
说明

string date_default_timezone_get ( void )

本函数返回默认时区,使用如下“假定”的顺序:

  • 用 date_default_timezone_set() 函数设定的时区(如果设定了的话)
  • 仅仅在 PHP 5.4.0 之前: TZ 环境变量(如果非空)
  • date.timezone 配置选项(如果设定了的话)
  • 仅仅在 PHP 5.4.0 之前: 查询操作系统主机 (如果操作系统支持并允许)。 This uses an algorithm that has to guess the timezone. This is by no means going to work correctly for every situation. A warning is shown when this stage is reached. Do not rely on it to be guessed correctly, and set date.timezone to the correct timezone instead.
  • 如果以上选择都不成功, date_default_timezone_get() 会则返回 UTC 的默认时区。
更新日志
版本 说明
5.4.0 不再使用 TZ 来推测时区。
5.4.0 不再根据操作系统的信息来推测时区,因为这是不可靠的。

例 #1 获取默认时区:

<?php
  date_default_timezone_set('Europe/London');
  if (date_default_timezone_get()) {
      echo 'date_default_timezone_set: ' . date_default_timezone_get() . '<br />';
  }
  if (ini_get('date.timezone')) {
      echo 'date.timezone: ' . ini_get('date.timezone');
  }
?>

以上例程的输出类似于:

date_default_timezone_set: Europe/London
date.timezone: Europe/London

例 #2 获取一个时区的简写:

<?php
  date_default_timezone_set('America/Los_Angeles');
  echo date_default_timezone_get() . ' => ' . date('e') . ' => ' . date('T');
?>

以上例程会输出:

America/Los_Angeles => America/Los_Angeles => PST

参见

  • date_default_timezone_set() - 设定用于一个脚本中所有日期时间函数的默认时区
  • 所支持的时区列表
Supported Date and Time Formats
DateTimeZone 类

命令行特有的扩展

压缩与归档扩展

信用卡处理

加密扩展

数据库扩展

抽象层

供应商特定数据库扩展

Mongo — MongoDB本地驱动
安装/配置
需求

构建此扩展不需要其他扩展。

安装

The MongoDB PHP driver should work on nearly any system: Windows, Mac OS X, Unix, and Linux; little- and big-endian machines; 32- and 64-bit machines; PHP 5.2, 5.3, 5.4 and 5.5.

此 » PECL 扩展未与 PHP 捆绑。

手动安装

For driver developers and people interested in the latest bugfixes, you can compile the driver from the latest source code on » Github. Go to Github and click the “download” button. Then run:

$ tar zxvf mongodb-mongodb-php-driver-<commit_id>.tar.gz
$ cd mongodb-mongodb-php-driver-<commit_id>
$ phpize
$ ./configure
$ make all
$ sudo make install

Make the following changes to php.ini:

Make sure the extension_dir variable is pointing to the directory containing mongo.so. The build will display where it is installing the PHP driver with output that looks something like:

Installing ‘/usr/lib/php/extensions/no-debug-non-zts-20060613/mongo.so’

Make sure that it is the same as the PHP extension directory by runnning:

$ php -i | grep extension_dir
  extension_dir => /usr/lib/php/extensions/no-debug-non-zts-20060613 =>
                   /usr/lib/php/extensions/no-debug-non-zts-20060613

If it’s not, change the extension_dir in php.ini or move mongo.so. To load the extension on PHP startup, add a line:

extension=mongo.so
在*NIX上安装

Run:

$ sudo pecl install mongo

If you are using CentOS or Redhat, you may wish to install from an » RPM.

Add the following line to your php.ini file:

extension=mongo.so

If pecl runs out of memory while installing, make sure memory_limit in php.ini is set to at least 128MB.

在Windows上安装

Precompiled binaries for each release are available from » Github for a variety of combinations of versions, thread safety, and VC libraries. Unzip the archive and put php_mongo.dll in your PHP extension directory (“ext” by default).

Add the following line to your php.ini file:

extension=php_mongo.dll
OS X

If your system is unable to find autoconf, you’ll need to install Xcode (available on your installation DVD or as a free download from the Apple website).

If you are using XAMPP, you may be able to compile the driver with the following command:

sudo /Applications/XAMPP/xamppfiles/bin/pecl install mongo

If you are using MAMP (or XAMPP and the above command does not work), precompiled binaries are available from » Github (download the latest one with “osx” in the name that matches your version of PHP). Extract mongo.so from the archive and add it to MAMP or XAMPP’s extension directory. Add

extension=mongo.so

to the php.ini file being used and restart the server.

Gentoo

Gentoo has a package for the PHP driver called dev-php5/mongo, which can be installed with:

$ sudo emerge -va dev-php5/mongo

If you use PECL, you may get an error that libtool is the wrong version. Compiling from source you’ll need to run aclocal and autoconf.

$ phpize
$ aclocal
$ autoconf
$ ./configure
$ make
$ sudo make install
Red Hat

This includes Fedora and CentOS.

The default Apache settings on these systems do not let requests make network connections, meaning that the driver will get “Permission denied” errors when it tries to connect to the database. If you run into this, try running:

$ /usr/sbin/setsebool -P httpd_can_network_connect 1

Then restart Apache. (This issue has also occurred with SELinux.)

第三方安装说明

A number of people have created excellent tutorials on installing the PHP driver.

» PHP 5.3.1 with Xdebug, MongoDB and Lithium on Ubuntu 9.10 / Apache 2.2

An excellent video that takes you step-by-step through installing Apache, PHP, Xdebug, MongoDB, and Lithium by Jon Adams.

» Installing MongoDB and the PHP driver on Ubuntu 9.04

Spanish article by Javier Aranda (» English translation).

» OS X: Installing MongoDB and the PHP Mongo Driver

By Matt Butcher.

运行配置
手册
手册
阅读参考
写关注

MongoDB provides several different ways of selecting how durable a write to the database should be. These ways are called Write Concerns and span everything from completely ignoring all errors, to specifically targetting which servers are required to confirm the write before returning the operation.

When a write (such as with MongoCollection::insert(), MongoCollection::update(), and MongoCollection::remove()) is given a Write Concern option (“w”) the driver will send the query to MongoDB and then followup with a getLastError command (GLE) with the Write Concern option which will be blocked until the Write Concern condition is verified to be fullfilled, or the query times out (controlled with the “wtimeout” option, no timeout by default).

警告

Even though a getLastError command times out the data will most likely have been written to the primary server and will be replicated to all the secondaries once they have cought up.

The typical reasons for a timeout to happen is if you specify a Write Concern which requires confirmation from more servers then you currently have available.

When using acknowledged writes and the replica set has failed over, the driver will automatically disconnect from the primary, throw an exception, and attempt to find a new primary on the next operation (your application must decide whether or not to retry the operation on the new primary).

When using unacknowledged writes (w=0) and the replica set has failed over, there will be no way for the driver to know about the change so it will continue and silently fail to write.

The default Write Concern for the MongoClient is 1: acknowledge write operations.

Available Write Concerns

Write Concern Meaning Description
w=0 Unacknowledged A write will not be followed up with a GLE call, and therefore not checked (“fire and forget”)
w=1 Acknowledged The write will be acknowledged by the server (the primary on replica set configuration)
w=N Replica Set Acknowledged The write will be acknowledged by the primary server, and replicated to N-1 secondaries.
w=majority Majority Acknowledged The write will be acknowledged by the majority of the replica set (including the primary). This is a special reserved string.
w=<tag set> Replica Set Tag Set Acknowledged The write will be acknowledged by members of the entire tag set
j=true Journaled The write will be acknowledged by primary and the journal flushed to disk
Unacknowledged Writes

By not requiring the server to acknowledge writes the writes can be performed extremely quickly, but you don’t know whether or not they actually succeeded. Writes can fail for a number of reasons: if there are network problems, if a database server goes down, or if the write was simply invalid (e.g., writing to a system collection; or duplicate key errors).

While developing, you should always use acknowledged writes (to protect against inadvertent mistakes, such as syntax errors, invalid operators, duplicate key errors and so on). In production, unacknowledged writes can be used for “unimportant” data. Unimportant data varies on application, but it’s generally automatically (instead of user generated) data, such as click tracking or GPS locations, where you can get thousands of records per second.

It is strongly recommended that you do an acknowledged write at the end of series of unacknowledged writes. Doing so will not incur in a too large performance penalty, but still allow you to catch any errors that may have occurred.

Example #1 Unacknowledged WriteConcern, followed with Acknowledged Write

<?php
  $collection->insert($someDoc, array("w" => 0));
  $collection->update($criteria, $newObj, array("w" => 0));
  $collection->insert($somethingElse, array("w" => 0));
  try {
      $collection->remove($something, array("w" => 1));
  } catch(MongoCursorException $e) {
      /* Handle the exception.. */
      /* Here we should issue find() queries on the IDs generated for
      $somethingElse and $someDoc to verify they got written to the database and
      attempt to figureout where in the chain something happened. */
  }
?>

If the last write throws an exception, you know that there’s a problem with your database. Acknowledged Writes

These type of write operations will make sure that the database has accepted the write operation before returning success. If the write failed, it will throw a MongoCursorException with an explanation of the failure. The MongoClient default behaviour is to acknowledge the write (w=1).

It is possible to specify how many members of an replica set have to acknowledge the write (i.e. have it replicated) before the write is deemed acknowledged and the operation returns.

Example #2 Acknowledged Writes

<?php
  // Force acknowledgement from the primary only
  $collection->insert($doc, array("w" => 1));

  // Force acknowledgement from the primary, and one other member of the
  // replica set
  $collection->insert($doc, array("w" => 2));

  // Force acknowledgement from the primary, and six other members of the
  // replica set (you probably never should do this):
  $collection->insert($doc, array("w" => 7));

Keep in mind to select your Write Concern carefully. If you have a replica set with 5 members, and you select Write Concern of 4 you will risk the write blocking forever when one member of the replica set goes down for maintenance or a temporary network outage happens. Warning Passing in a string value for Write Concern has a specific meaning (Replica Set Tag Set Acknowledged). Please be careful of NOT using string values for numbers (i.e. array(“w” => “1”)) as it will be treated as a tag set name.

Majority Acknowledged Writes

Using the special majority Write Concern option is the recommended way for writes that are required to survive the apocalypse, as it will ensure the majority of your replica set will have the write and will therefore be guaranteed to survive all usual suspect outage scenarios.

Example #3 Majority Acknowledged Write

<?php
  $collection->insert($someDoc, array("w" => "majority"));
?>
Journaled Writes

When connecting to a replica set the default Write Concern is only to have the primary server acknowledge the write. There is however a 100ms window until the write gets journaled and flushed to disk. It is possible to force the write to be journaled before acknowledging the write by setting the j option:

Example #4 Acknowledged and Journaled Write Forcing journal flush

<?php
  $options = array(
   "w" => 1,
   "j" => true,
);
try {
   $collection->insert($document, $options);
} catch(MongoCursorException $e) {
   /* handle the exception */
}

参见

» MongoDB WriteConcern docs

更新日志
版本 说明
1.3.0 MongoClient was introduced and defaults to acknowledged writes. The deprecated Mongo defaults to unacknowledged writes.
1.3.0 The “safe” write option has been deprecated and is not available with the new MongoClient class. Use the “w” option instead.
SQL to Mongo Mapping Chart
Connecting
Writes
Querying
Updates
Security
Troubleshooting
Running the Driver’s Tests
核心类
MongoClient
MongoDB
MongoCollection
MongoCursor
类型
MongoId
MongoCode
MongoDate
MongoRegex
MongoBinData
MongoInt32
MongoInt64
MongoDBRef
MongoMinKey
MongoMaxKey
MongoTimestamp
GridFS类
MongoGridFS类

(PECL mongo >=0.9.0)

介绍

Utilities for storing and retrieving files from the database.

GridFS is a storage specification all supported drivers implement. Basically, it defines two collections: files, for file metadata, and chunks, for file content. If the file is large, it will automatically be split into smaller chunks and each chunk will be saved as a document in the chunks collection.

Each document in the files collection contains the filename, upload date, and md5 hash. It also contains a unique _id field, which can be used to query the chunks collection for the file’s content. Each document in the chunks collection contains a chunk of binary data, a files_id field that matches its file’s _id, and the position of this chunk in the overall file.

例如, 文件文档如下:

<?php
  array("_id" => 123456789, "filename" => "foo.txt", "chunkSize" => 3, "length" => 12);
?>

块文件如下:

<?php
 array("files_id" => 123456789, "n" => 0, "data" => new MongoBinData("abc"));
 array("files_id" => 123456789, "n" => 1, "data" => new MongoBinData("def"));
 array("files_id" => 123456789, "n" => 2, "data" => new MongoBinData("ghi"));
 array("files_id" => 123456789, "n" => 3, "data" => new MongoBinData("jkl"));
?>

当然, 默认块大小是千字节, but that makes an unwieldy example.

跨语言兼容

You should be able to use any files created by MongoGridFS with any other drivers, and vice versa. However, some drivers expect that all metadata associated with a file be in a “metadata” field. If you’re going to be using other languages, it’s a good idea to wrap info you might want them to see in a “metadata” field. For example, instead of:

<?php
 $grid->storeFile("somefile.txt", array("date" => new MongoDate()));
?>

use something like:

<?php
 $grid->storeFile("somefile.txt", array("metadata" => array("date" => new MongoDate())));
?>
MongoGridFS家庭

MongoGridFS represents the files and chunks collections. MongoGridFS extends MongoCollection, and an instance of MongoGridFS has access to all of MongoCollection methods, which act on the files collection:

<?php
 $grid = $db->getGridFS();
 $grid->update(array("filename" => "foo"), $newObj); // update on the files collection
?>

另一个操作元数据实例:

<?php
 // 保存文件
 $id = $grid->storeFile("game.tgz");
 $game = $grid->findOne();
 // 添加一个下载计数器
 $game->file['downloads'] = 0;
 $grid->save($game->file);
 // 累加计数器
 $grid->update(array("_id" => $id), array('$inc' => array("downloads" => 1)));
?>

你也可以从MongoGridFS实例访问块集合:

<?php
 $chunks = $grid->chunks; // $chunks is a normal MongoCollection
 $chunks->insert(array("x" => 4));
?>

There are some methods for MongoGridFS with the same name as MongoCollection methods, that behave slightly differently. For example, MongoGridFS::remove() will remove any objects that match the criteria from the files collection and their content from the chunks collection.

To store something new in GridFS, there are a couple options. If you have a filename, you can say:

<?php
 $grid->storeFile($filename, array("whatever" => "metadata", "you" => "want"));
?>

If you have a string of bytes that isn’t a file, you can also store that using MongoGridFS::storeBytes():

<?php
 $grid->storeBytes($bytes, array("whatever" => "metadata", "you" => "want"));
?>

Querying a MongoGridFS collection returns a MongoGridFSCursor, which behaves like a normal MongoCursor except that it returns MongoGridFSFiles instead of associative arrays.

MongoGridFSFiles can be written back to disc using MongoGridFSFile::write() or retrieved in memory using MongoGridFSFile::getBytes(). There is currently no method that automatically streams chunks, but it would be fairly easy to write by querying the $grid->chunks collection.

MongoGridFSFile objects contain a field file which contains any file metadata.

类简介
<?PHP
extends MongoCollection {
 /* Fields */
 public MongoCollection $chunks = NULL ;
 protected string $filesName = NULL ;
 protected string $chunksName = NULL ;
 /* Methods */
 public __construct ( MongoDB $db [, string $prefix = "fs" [, mixed $chunks = "fs" ]] )
 public bool delete ( mixed $id )
 public array drop ( void )
 public MongoGridFSCursor find ([ array $query = array() [, array $fields = array() ]] )
 public MongoGridFSFile findOne ([ mixed $query = array() [, mixed $fields = array() ]] )
 public MongoGridFSFile get ( mixed $id )
 public mixed put ( string $filename [, array $metadata = array() ] )
 public bool remove ([ array $criteria = array() [, array $options = array() ]] )
 public mixed storeBytes ( string $bytes [, array $metadata = array() [, array $options = array() ]] )
 public mixed storeFile ( string $filename [, array $metadata = array() [, array $options = array() ]] )
 public mixed storeUpload ( string $name [, array $metadata ] )
}
?>
参见

MongoDB 核心文档 » GridFS

LightCube Solutions blog post on » MongoDB和PHP – GridFS快速浏览

LightCube Solutions blog post on » 在MongoDB/PHP里添加元数据到文件里

MongoGridFSFile类

(PECL mongo >=0.9.0)

介绍

A database file object.

类简介
<?PHP
MongoGridFSFile {
 /* Fields */
 public array $file = NULL ;
 protected MongoGridFS $gridfs = NULL ;
 /* Methods */
 public MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )
 public string getBytes ( void )
 public string getFilename ( void )
 public stream getResource ( void )
 public int getSize ( void )
 public int write ([ string $filename = NULL ] )
}
?>
MongoGridFSCursor类

(PECL mongo >=0.9.0)

介绍

Cursor for database file results.

类简介
<?PHP
  extends MongoCursor {
   /* Fields */
   protected MongoGridFS $gridfs = NULL ;
   /* Methods */
   public __construct ( MongoGridFS $gridfs , resource $connection , string $ns , array $query , array $fields )
   public MongoGridFSFile current ( void )
   public MongoGridFSFile getNext ( void )
  public string key ( void )
 }
?>
杂项
MongoLog
MongoPool
Mongo
Mongo 函数
bson_decode
bson_decode
异常
bson_decode
MongoResultException
MongoCursorException
MongoCursorTimeoutException
MongoCursorTimeoutException
MongoGridFSException
变更日志
变更日志

文件系统相关扩展

国际化与字符编码支持

图像生成和处理

Cairo

Exif

GD

Gmagick

ImageMagick

简介

imagick的是原生的PHP扩展使用ImageMagick API来创建和修改图像。

ImageMagick® is a software suite to create, edit, and compose bitmap images.. It can read, convert and write images in a variety of formats (over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF.

Copyright 1999-2007 ImageMagick Studio LLC, a non-profit organization dedicated to making software imaging solutions freely available.

安装配置
需求
Installation requirements on Windows

Version information does not differ from that above. There are binaries available from http://www.imagemagick.org/ so that you can load this extension on Windows without need for a compiler.

Installation requirements on other platforms

PHP >= 5.1.3 and ImageMagick >= 6.2.4 is required. The amount of formats supported is by Imagick is entirely dependent upon the amount of formats supported by your ImageMagick installation. For example, Imagemagick requires ghostscript to conduct PDF operations.

安装

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/imagick.

Note: The official name of this extension is imagick.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

#yum install ImageMagick*
#pecl install imagick

sometimes you may have ask to install gcc compiler. if so execute

#yum install gcc*

added the extension on php.ini

#echo "extension=imagick.so" >> /etc/php.ini
#service httpd restart
配置

The behaviour of these functions is affected by settings in php.ini.

Imagick configuration options Name Default Changeable Changelog imagick.locale_fix FALSE PHP_INI_ALL Available since Imagick 2.1.0 imagick.progress_monitor FALSE PHP_INI_SYSTEM Available since Imagick 2.2.2 For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set. Here’s a short explanation of the configuration directives.

imagick.locale_fix boolean Fixes a drawing bug with locales that use ‘,’ as float separators.

imagick.progress_monitor boolean Used to enable the image progress monitor.

资源类型
预定义的常量

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

COLOR_* constants Colortype constants. These constants are mainly used with ImagickPixel.

imagick::COLOR_BLACK (integer) Black color imagick::COLOR_BLUE (integer) Blue color imagick::COLOR_CYAN (integer) Cyan color imagick::COLOR_GREEN (integer) Green color imagick::COLOR_RED (integer) Red color imagick::COLOR_YELLOW (integer) Yellow color imagick::COLOR_MAGENTA (integer) Magenta color imagick::COLOR_OPACITY (integer) Color’s opacity imagick::COLOR_ALPHA (integer) Color’s alpha imagick::COLOR_FUZZ (integer) Color’s fuzz DISPOSE constants Dispose type constants

imagick::DISPOSE_UNRECOGNIZED (integer) Unrecognized dispose type imagick::DISPOSE_UNDEFINED (integer) Undefined dispose type imagick::DISPOSE_NONE (integer) No dispose type defined imagick::DISPOSE_BACKGROUND (integer) Dispose background imagick::DISPOSE_PREVIOUS (integer) Dispose previous Composite Operator Constants imagick::COMPOSITE_DEFAULT (integer) The default composite operator imagick::COMPOSITE_UNDEFINED (integer) Undefined composite operator imagick::COMPOSITE_NO (integer) No composite operator defined imagick::COMPOSITE_ADD (integer) The result of image + image imagick::COMPOSITE_ATOP (integer) The result is the same shape as image, with composite image obscuring image where the image shapes overlap imagick::COMPOSITE_BLEND (integer) Blends the image imagick::COMPOSITE_BUMPMAP (integer) The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first. imagick::COMPOSITE_CLEAR (integer) Makes the target image transparent imagick::COMPOSITE_COLORBURN (integer) Darkens the destination image to reflect the source image imagick::COMPOSITE_COLORDODGE (integer) Brightens the destination image to reflect the source image imagick::COMPOSITE_COLORIZE (integer) Colorizes the target image using the composite image imagick::COMPOSITE_COPYBLACK (integer) Copies black from the source to target imagick::COMPOSITE_COPYBLUE (integer) Copies blue from the source to target imagick::COMPOSITE_COPY (integer) Copies the source image on the target image imagick::COMPOSITE_COPYCYAN (integer) Copies cyan from the source to target imagick::COMPOSITE_COPYGREEN (integer) Copies green from the source to target imagick::COMPOSITE_COPYMAGENTA (integer) Copies magenta from the source to target imagick::COMPOSITE_COPYOPACITY (integer) Copies opacity from the source to target imagick::COMPOSITE_COPYRED (integer) Copies red from the source to target imagick::COMPOSITE_COPYYELLOW (integer) Copies yellow from the source to target imagick::COMPOSITE_DARKEN (integer) Darkens the target image imagick::COMPOSITE_DSTATOP (integer) The part of the destination lying inside of the source is composited over the source and replaces the destination imagick::COMPOSITE_DST (integer) The target is left untouched imagick::COMPOSITE_DSTIN (integer) The parts inside the source replace the target imagick::COMPOSITE_DSTOUT (integer) The parts outside the source replace the target imagick::COMPOSITE_DSTOVER (integer) Target replaces the source imagick::COMPOSITE_DIFFERENCE (integer) Subtracts the darker of the two constituent colors from the lighter imagick::COMPOSITE_DISPLACE (integer) Shifts target image pixels as defined by the source imagick::COMPOSITE_DISSOLVE (integer) Dissolves the source in to the target imagick::COMPOSITE_EXCLUSION (integer) Produces an effect similar to that of imagick::COMPOSITE_DIFFERENCE, but appears as lower contrast imagick::COMPOSITE_HARDLIGHT (integer) Multiplies or screens the colors, dependent on the source color value imagick::COMPOSITE_HUE (integer) Modifies the hue of the target as defined by source imagick::COMPOSITE_IN (integer) Composites source into the target imagick::COMPOSITE_LIGHTEN (integer) Lightens the target as defined by source imagick::COMPOSITE_LUMINIZE (integer) Luminizes the target as defined by source imagick::COMPOSITE_MINUS (integer) Subtracts the source from the target imagick::COMPOSITE_MODULATE (integer) Modulates the target brightness, saturation and hue as defined by source imagick::COMPOSITE_MULTIPLY (integer) Multiplies the target to the source imagick::COMPOSITE_OUT (integer) Composites outer parts of the source on the target imagick::COMPOSITE_OVER (integer) Composites source over the target imagick::COMPOSITE_OVERLAY (integer) Overlays the source on the target imagick::COMPOSITE_PLUS (integer) Adds the source to the target imagick::COMPOSITE_REPLACE (integer) Replaces the target with the source imagick::COMPOSITE_SATURATE (integer) Saturates the target as defined by the source imagick::COMPOSITE_SCREEN (integer) The source and destination are complemented and then multiplied and then replace the destination imagick::COMPOSITE_SOFTLIGHT (integer) Darkens or lightens the colors, dependent on the source imagick::COMPOSITE_SRCATOP (integer) The part of the source lying inside of the destination is composited onto the destination imagick::COMPOSITE_SRC (integer) The source is copied to the destination imagick::COMPOSITE_SRCIN (integer) The part of the source lying inside of the destination replaces the destination imagick::COMPOSITE_SRCOUT (integer) The part of the source lying outside of the destination replaces the destination imagick::COMPOSITE_SRCOVER (integer) The source replaces the destination imagick::COMPOSITE_SUBTRACT (integer) Subtract the colors in the source image from the destination image imagick::COMPOSITE_THRESHOLD (integer) The source is composited on the target as defined by source threshold imagick::COMPOSITE_XOR (integer) The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source MONTAGEMODE constants imagick::MONTAGEMODE_FRAME (integer) imagick::MONTAGEMODE_UNFRAME (integer) imagick::MONTAGEMODE_CONCATENATE (integer) STYLE constants imagick::STYLE_NORMAL (integer) imagick::STYLE_ITALIC (integer) imagick::STYLE_OBLIQUE (integer) imagick::STYLE_ANY (integer) FILTER constants imagick::FILTER_UNDEFINED (integer) imagick::FILTER_POINT (integer) imagick::FILTER_BOX (integer) imagick::FILTER_TRIANGLE (integer) imagick::FILTER_HERMITE (integer) imagick::FILTER_HANNING (integer) imagick::FILTER_HAMMING (integer) imagick::FILTER_BLACKMAN (integer) imagick::FILTER_GAUSSIAN (integer) imagick::FILTER_QUADRATIC (integer) imagick::FILTER_CUBIC (integer) imagick::FILTER_CATROM (integer) imagick::FILTER_MITCHELL (integer) imagick::FILTER_LANCZOS (integer) imagick::FILTER_BESSEL (integer) imagick::FILTER_SINC (integer) IMGTYPE constants imagick::IMGTYPE_UNDEFINED (integer) imagick::IMGTYPE_BILEVEL (integer) imagick::IMGTYPE_GRAYSCALE (integer) imagick::IMGTYPE_GRAYSCALEMATTE (integer) imagick::IMGTYPE_PALETTE (integer) imagick::IMGTYPE_PALETTEMATTE (integer) imagick::IMGTYPE_TRUECOLOR (integer) imagick::IMGTYPE_TRUECOLORMATTE (integer) imagick::IMGTYPE_COLORSEPARATION (integer) imagick::IMGTYPE_COLORSEPARATIONMATTE (integer) imagick::IMGTYPE_OPTIMIZE (integer) RESOLUTION constants imagick::RESOLUTION_UNDEFINED (integer) imagick::RESOLUTION_PIXELSPERINCH (integer) imagick::RESOLUTION_PIXELSPERCENTIMETER (integer) COMPRESSION constants imagick::COMPRESSION_UNDEFINED (integer) imagick::COMPRESSION_NO (integer) imagick::COMPRESSION_BZIP (integer) imagick::COMPRESSION_FAX (integer) imagick::COMPRESSION_GROUP4 (integer) imagick::COMPRESSION_JPEG (integer) imagick::COMPRESSION_JPEG2000 (integer) imagick::COMPRESSION_LOSSLESSJPEG (integer) imagick::COMPRESSION_LZW (integer) imagick::COMPRESSION_RLE (integer) imagick::COMPRESSION_ZIP (integer) imagick::COMPRESSION_DXT1 (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher. imagick::COMPRESSION_DXT3 (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher. imagick::COMPRESSION_DXT5 (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher. PAINT constants imagick::PAINT_POINT (integer) imagick::PAINT_REPLACE (integer) imagick::PAINT_FLOODFILL (integer) imagick::PAINT_FILLTOBORDER (integer) imagick::PAINT_RESET (integer) GRAVITY constants imagick::GRAVITY_NORTHWEST (integer) imagick::GRAVITY_NORTH (integer) imagick::GRAVITY_NORTHEAST (integer) imagick::GRAVITY_WEST (integer) imagick::GRAVITY_CENTER (integer) imagick::GRAVITY_EAST (integer) imagick::GRAVITY_SOUTHWEST (integer) imagick::GRAVITY_SOUTH (integer) imagick::GRAVITY_SOUTHEAST (integer) STRETCH constants imagick::STRETCH_NORMAL (integer) imagick::STRETCH_ULTRACONDENSED (integer) imagick::STRETCH_CONDENSED (integer) imagick::STRETCH_SEMICONDENSED (integer) imagick::STRETCH_SEMIEXPANDED (integer) imagick::STRETCH_EXPANDED (integer) imagick::STRETCH_EXTRAEXPANDED (integer) imagick::STRETCH_ULTRAEXPANDED (integer) imagick::STRETCH_ANY (integer) ALIGN constants imagick::ALIGN_UNDEFINED (integer) imagick::ALIGN_LEFT (integer) imagick::ALIGN_CENTER (integer) imagick::ALIGN_RIGHT (integer) DECORATION constants imagick::DECORATION_NO (integer) imagick::DECORATION_UNDERLINE (integer) imagick::DECORATION_OVERLINE (integer) imagick::DECORATION_LINETROUGH (integer) NOISE constants imagick::NOISE_UNIFORM (integer) imagick::NOISE_GAUSSIAN (integer) imagick::NOISE_MULTIPLICATIVEGAUSSIAN (integer) imagick::NOISE_IMPULSE (integer) imagick::NOISE_LAPLACIAN (integer) imagick::NOISE_POISSON (integer) imagick::NOISE_RANDOM (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher. CHANNEL constants imagick::CHANNEL_UNDEFINED (integer) imagick::CHANNEL_RED (integer) imagick::CHANNEL_GRAY (integer) imagick::CHANNEL_CYAN (integer) imagick::CHANNEL_GREEN (integer) imagick::CHANNEL_MAGENTA (integer) imagick::CHANNEL_BLUE (integer) imagick::CHANNEL_YELLOW (integer) imagick::CHANNEL_ALPHA (integer) imagick::CHANNEL_OPACITY (integer) imagick::CHANNEL_MATTE (integer) imagick::CHANNEL_BLACK (integer) imagick::CHANNEL_INDEX (integer) imagick::CHANNEL_ALL (integer) imagick::CHANNEL_DEFAULT (integer) METRIC constants imagick::METRIC_UNDEFINED (integer) imagick::METRIC_MEANABSOLUTEERROR (integer) imagick::METRIC_MEANSQUAREERROR (integer) imagick::METRIC_PEAKABSOLUTEERROR (integer) imagick::METRIC_PEAKSIGNALTONOISERATIO (integer) imagick::METRIC_ROOTMEANSQUAREDERROR (integer) PIXEL constants imagick::PIXEL_CHAR (integer) imagick::PIXEL_DOUBLE (integer) imagick::PIXEL_FLOAT (integer) imagick::PIXEL_INTEGER (integer) imagick::PIXEL_LONG (integer) imagick::PIXEL_QUANTUM (integer) imagick::PIXEL_SHORT (integer) EVALUATE constants imagick::EVALUATE_UNDEFINED (integer) imagick::EVALUATE_ADD (integer) imagick::EVALUATE_AND (integer) imagick::EVALUATE_DIVIDE (integer) imagick::EVALUATE_LEFTSHIFT (integer) imagick::EVALUATE_MAX (integer) imagick::EVALUATE_MIN (integer) imagick::EVALUATE_MULTIPLY (integer) imagick::EVALUATE_OR (integer) imagick::EVALUATE_RIGHTSHIFT (integer) imagick::EVALUATE_SET (integer) imagick::EVALUATE_SUBTRACT (integer) imagick::EVALUATE_XOR (integer) imagick::EVALUATE_POW (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_LOG (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_THRESHOLD (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_THRESHOLDBLACK (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_THRESHOLDWHITE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_GAUSSIANNOISE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_IMPULSENOISE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_LAPLACIANNOISE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_MULTIPLICATIVENOISE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_POISSONNOISE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_UNIFORMNOISE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_COSINE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_SINE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. imagick::EVALUATE_ADDMODULUS (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher. COLORSPACE constants imagick::COLORSPACE_UNDEFINED (integer) imagick::COLORSPACE_RGB (integer) imagick::COLORSPACE_GRAY (integer) imagick::COLORSPACE_TRANSPARENT (integer) imagick::COLORSPACE_OHTA (integer) imagick::COLORSPACE_LAB (integer) imagick::COLORSPACE_XYZ (integer) imagick::COLORSPACE_YCBCR (integer) imagick::COLORSPACE_YCC (integer) imagick::COLORSPACE_YIQ (integer) imagick::COLORSPACE_YPBPR (integer) imagick::COLORSPACE_YUV (integer) imagick::COLORSPACE_CMYK (integer) imagick::COLORSPACE_SRGB (integer) imagick::COLORSPACE_HSB (integer) imagick::COLORSPACE_HSL (integer) imagick::COLORSPACE_HWB (integer) imagick::COLORSPACE_REC601LUMA (integer) imagick::COLORSPACE_REC709LUMA (integer) imagick::COLORSPACE_LOG (integer) imagick::COLORSPACE_CMY (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher. VIRTUALPIXELMETHOD constants imagick::VIRTUALPIXELMETHOD_UNDEFINED (integer) imagick::VIRTUALPIXELMETHOD_BACKGROUND (integer) imagick::VIRTUALPIXELMETHOD_CONSTANT (integer) imagick::VIRTUALPIXELMETHOD_EDGE (integer) imagick::VIRTUALPIXELMETHOD_MIRROR (integer) imagick::VIRTUALPIXELMETHOD_TILE (integer) imagick::VIRTUALPIXELMETHOD_TRANSPARENT (integer) imagick::VIRTUALPIXELMETHOD_MASK (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher. imagick::VIRTUALPIXELMETHOD_BLACK (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher. imagick::VIRTUALPIXELMETHOD_GRAY (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher. imagick::VIRTUALPIXELMETHOD_WHITE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher. imagick::VIRTUALPIXELMETHOD_HORIZONTALTILE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.3 or higher. imagick::VIRTUALPIXELMETHOD_VERTICALTILE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.3 or higher. PREVIEW constants imagick::PREVIEW_UNDEFINED (integer) imagick::PREVIEW_ROTATE (integer) imagick::PREVIEW_SHEAR (integer) imagick::PREVIEW_ROLL (integer) imagick::PREVIEW_HUE (integer) imagick::PREVIEW_SATURATION (integer) imagick::PREVIEW_BRIGHTNESS (integer) imagick::PREVIEW_GAMMA (integer) imagick::PREVIEW_SPIFF (integer) imagick::PREVIEW_DULL (integer) imagick::PREVIEW_GRAYSCALE (integer) imagick::PREVIEW_QUANTIZE (integer) imagick::PREVIEW_DESPECKLE (integer) imagick::PREVIEW_REDUCENOISE (integer) imagick::PREVIEW_ADDNOISE (integer) imagick::PREVIEW_SHARPEN (integer) imagick::PREVIEW_BLUR (integer) imagick::PREVIEW_THRESHOLD (integer) imagick::PREVIEW_EDGEDETECT (integer) imagick::PREVIEW_SPREAD (integer) imagick::PREVIEW_SOLARIZE (integer) imagick::PREVIEW_SHADE (integer) imagick::PREVIEW_RAISE (integer) imagick::PREVIEW_SEGMENT (integer) imagick::PREVIEW_SWIRL (integer) imagick::PREVIEW_IMPLODE (integer) imagick::PREVIEW_WAVE (integer) imagick::PREVIEW_OILPAINT (integer) imagick::PREVIEW_CHARCOALDRAWING (integer) imagick::PREVIEW_JPEG (integer) RENDERINGINTENT constants imagick::RENDERINGINTENT_UNDEFINED (integer) imagick::RENDERINGINTENT_SATURATION (integer) imagick::RENDERINGINTENT_PERCEPTUAL (integer) imagick::RENDERINGINTENT_ABSOLUTE (integer) imagick::RENDERINGINTENT_RELATIVE (integer) INTERLACE constants imagick::INTERLACE_UNDEFINED (integer) imagick::INTERLACE_NO (integer) imagick::INTERLACE_LINE (integer) imagick::INTERLACE_PLANE (integer) imagick::INTERLACE_PARTITION (integer) imagick::INTERLACE_GIF (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.4 or higher. imagick::INTERLACE_JPEG (integer) imagick::INTERLACE_PNG (integer) FILLRULE constants imagick::FILLRULE_UNDEFINED (integer) imagick::FILLRULE_EVENODD (integer) imagick::FILLRULE_NONZERO (integer) PATHUNITS constants imagick::PATHUNITS_UNDEFINED (integer) imagick::PATHUNITS_USERSPACE (integer) imagick::PATHUNITS_USERSPACEONUSE (integer) imagick::PATHUNITS_OBJECTBOUNDINGBOX (integer) LINECAP constants imagick::LINECAP_UNDEFINED (integer) imagick::LINECAP_BUTT (integer) imagick::LINECAP_ROUND (integer) imagick::LINECAP_SQUARE (integer) LINEJOIN constants imagick::LINEJOIN_UNDEFINED (integer) imagick::LINEJOIN_MITER (integer) imagick::LINEJOIN_ROUND (integer) imagick::LINEJOIN_BEVEL (integer) RESOURCETYPE constants imagick::RESOURCETYPE_UNDEFINED (integer) imagick::RESOURCETYPE_AREA (integer) imagick::RESOURCETYPE_DISK (integer) imagick::RESOURCETYPE_FILE (integer) imagick::RESOURCETYPE_MAP (integer) imagick::RESOURCETYPE_MEMORY (integer) LAYERMETHOD constants imagick::LAYERMETHOD_UNDEFINED (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher. imagick::LAYERMETHOD_COALESCE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher. imagick::LAYERMETHOD_COMPAREANY (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher. imagick::LAYERMETHOD_COMPARECLEAR (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher. imagick::LAYERMETHOD_COMPAREOVERLAY (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher. imagick::LAYERMETHOD_DISPOSE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher. imagick::LAYERMETHOD_OPTIMIZE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher. imagick::LAYERMETHOD_OPTIMIZEPLUS (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher. imagick::LAYERMETHOD_OPTIMIZEIMAGE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::LAYERMETHOD_OPTIMIZETRANS (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::LAYERMETHOD_REMOVEDUPS (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::LAYERMETHOD_REMOVEZERO (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::LAYERMETHOD_COMPOSITE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::LAYERMETHOD_MERGE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher. imagick::LAYERMETHOD_FLATTEN (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher. imagick::LAYERMETHOD_MOSAIC (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher. ORIENTATION constants imagick::ORIENTATION_UNDEFINED (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::ORIENTATION_TOPLEFT (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::ORIENTATION_TOPRIGHT (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::ORIENTATION_BOTTOMRIGHT (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::ORIENTATION_BOTTOMLEFT (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::ORIENTATION_LEFTTOP (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::ORIENTATION_RIGHTTOP (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::ORIENTATION_RIGHTBOTTOM (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. imagick::ORIENTATION_LEFTBOTTOM (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher. DISTORTION constants imagick::DISTORTION_UNDEFINED (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher. imagick::DISTORTION_AFFINE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher. imagick::DISTORTION_AFFINEPROJECTION (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher. imagick::DISTORTION_ARC (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher. imagick::DISTORTION_BILINEAR (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher. imagick::DISTORTION_PERSPECTIVE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher. imagick::DISTORTION_PERSPECTIVEPROJECTION (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher. imagick::DISTORTION_SCALEROTATETRANSLATE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher. imagick::DISTORTION_POLYNOMIAL (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::DISTORTION_POLAR (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::DISTORTION_DEPOLAR (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::DISTORTION_BARREL (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::DISTORTION_BARRELINVERSE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::DISTORTION_SHEPARDS (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::DISTORTION_SENTINEL (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. ALPHACHANNEL constants imagick::ALPHACHANNEL_ACTIVATE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher. imagick::ALPHACHANNEL_DEACTIVATE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher. imagick::ALPHACHANNEL_RESET (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher. imagick::ALPHACHANNEL_SET (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher. imagick::ALPHACHANNEL_UNDEFINED (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::ALPHACHANNEL_COPY (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::ALPHACHANNEL_EXTRACT (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::ALPHACHANNEL_OPAQUE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::ALPHACHANNEL_SHAPE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::ALPHACHANNEL_TRANSPARENT (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. SPARSECOLORMETHOD constants imagick::SPARSECOLORMETHOD_UNDEFINED (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::SPARSECOLORMETHOD_BARYCENTRIC (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::SPARSECOLORMETHOD_BILINEAR (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::SPARSECOLORMETHOD_POLYNOMIAL (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::SPARSECOLORMETHOD_SPEPARDS (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::SPARSECOLORMETHOD_VORONOI (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. FUNCTION constants imagick::FUNCTION_UNDEFINED (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher. imagick::FUNCTION_POLYNOMIAL (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher. imagick::FUNCTION_SINUSOID (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher. INTERPOLATE constants imagick::INTERPOLATE_UNDEFINED (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher. imagick::INTERPOLATE_AVERAGE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher. imagick::INTERPOLATE_BICUBIC (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher. imagick::INTERPOLATE_BILINEAR (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher. imagick::INTERPOLATE_FILTER (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher. imagick::INTERPOLATE_INTEGER (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher. imagick::INTERPOLATE_MESH (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher. imagick::INTERPOLATE_NEARESTNEIGHBOR (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher. imagick::INTERPOLATE_SPLINE (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.3.4 or higher. DITHERMETHOD constants imagick::DITHERMETHOD_UNDEFINED (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::DITHERMETHOD_NO (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::DITHERMETHOD_RIEMERSMA (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher. imagick::DITHERMETHOD_FLOYDSTEINBERG (integer) This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.

实例

Imagick makes image manipulation in PHP extremely easy through an OO interface. Here is a quick example on how to make a thumbnail:

例 #1 使用Imagick创建缩略图

<?php
 header('Content-type: image/jpeg');
 $image = new Imagick('image.jpg');
 // If 0 is provided as a width or height parameter,
 // aspect ratio is maintained
 $image->thumbnailImage(100, 0);
 echo $image;
?>

Using SPL and other OO features supported in Imagick, it can be simple to resize all files in a directory (useful for batch resizing large digital camera images to be web viewable). Here we use resize, as we might want to retain certain meta-data:

Example #2 Make a thumbnail of all JPG files in a directory

<?php
 $images = new Imagick(glob('images/*.JPG'));
 foreach($images as $image) {
   // Providing 0 forces thumbnailImage to maintain aspect ratio
   $image->thumbnailImage(1024,0);
 }
 $images->writeImages();
?>

This is an example of creating a reflection of an image. The reflection is created by flipping the image and overlaying a gradient on it. Then both, the original image and the reflection is overlayed on a canvas.

Example #3 Creating a reflection of an image

<?php
 /* Read the image */
 $im = new Imagick("test.png");
 /* Thumbnail the image */
 $im->thumbnailImage(200, null);
 /* Create a border for the image */
 $im->borderImage(new ImagickPixel("white"), 5, 5);
 /* Clone the image and flip it */
 $reflection = $im->clone();
 $reflection->flipImage();
 /* Create gradient. It will be overlayed on the reflection */
 $gradient = new Imagick();
 /* Gradient needs to be large enough for the image and the borders */
 $gradient->newPseudoImage($reflection->getImageWidth() + 10, $reflection->getImageHeight() + 10, "gradient:transparent-black");
 /* Composite the gradient on the reflection */
 $reflection->compositeImage($gradient, imagick::COMPOSITE_OVER, 0, 0);
 /* Add some opacity. Requires ImageMagick 6.2.9 or later */
 $reflection->setImageOpacity( 0.3 );
 /* Create an empty canvas */
 $canvas = new Imagick();
 /* Canvas needs to be large enough to hold the both images */
 $width = $im->getImageWidth() + 40;
 $height = ($im->getImageHeight() * 2) + 30;
 $canvas->newImage($width, $height, new ImagickPixel("black"));
 $canvas->setImageFormat("png");
 /* Composite the original image and the reflection on the canvas */
 $canvas->compositeImage($im, imagick::COMPOSITE_OVER, 20, 10);
 $canvas->compositeImage($reflection, imagick::COMPOSITE_OVER, 20, $im->getImageHeight() + 10);
 /* Output the image*/
 header("Content-Type: image/png");
 echo $canvas;
?>

The above example will output something similar to:

This example illustrates how to use fill patterns during drawing.

Example #4 Filling text with gradient

<?php
 /* Create a new imagick object */
 $im = new Imagick();
 /* Create new image. This will be used as fill pattern */
 $im->newPseudoImage(50, 50, "gradient:red-black");
 /* Create imagickdraw object */
 $draw = new ImagickDraw();
 /* Start a new pattern called "gradient" */
 $draw->pushPattern('gradient', 0, 0, 50, 50);
 /* Composite the gradient on the pattern */
 $draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 50, 50, $im);
 /* Close the pattern */
 $draw->popPattern();
 /* Use the pattern called "gradient" as the fill */
 $draw->setFillPatternURL('#gradient');
 /* Set font size to 52 */
 $draw->setFontSize(52);
 /* Annotate some text */
 $draw->annotation(20, 50, "Hello World!");
 /* Create a new canvas object and a white image */
 $canvas = new Imagick();
 $canvas->newImage(350, 70, "white");
 /* Draw the ImagickDraw on to the canvas */
 $canvas->drawImage($draw);
 /* 1px black border around the image */
 $canvas->borderImage('black', 1, 1);
 /* Set the format to PNG */
 $canvas->setImageFormat('png');
 /* Output the image */
 header("Content-Type: image/png");
 echo $canvas;
?>

The above example will output something similar to:

Working with animated GIF images

Example #5 Read in GIF image and resize all frames

<?php
 /* Create a new imagick object and read in GIF */
 $im = new Imagick("example.gif");
 /* Resize all frames */
 foreach ($im as $frame) {
     /* 50x50 frames */
     $frame->thumbnailImage(50, 50);
     /* Set the virtual canvas to correct size */
     $frame->setImagePage(50, 50, 0, 0);
 }
 /* Notice writeImages instead of writeImage */
 $im->writeImages("example_small.gif", true);
?>

Working with ellipse primitive and custom fonts

Example #6 Create a PHP logo

<?php
 /* Set width and height in proportion of genuine PHP logo */
 $width = 400;
 $height = 210;
 /* Create an Imagick object with transparent canvas */
 $img = new Imagick();
 $img->newImage($width, $height, new ImagickPixel('transparent'));
 /* New ImagickDraw instance for ellipse draw */
 $draw = new ImagickDraw();
 /* Set purple fill color for ellipse */
 $draw->setFillColor('#777bb4');
 /* Set ellipse dimensions */
 $draw->ellipse($width / 2, $height / 2, $width / 2, $height / 2, 0, 360);
 /* Draw ellipse onto the canvas */
 $img->drawImage($draw);
 /* Reset fill color from purple to black for text (note: we are reusing ImagickDraw object) */
 $draw->setFillColor('black');
 /* Set stroke border to white color */
 $draw->setStrokeColor('white');
 /* Set stroke border thickness */
 $draw->setStrokeWidth(2);
 /* Set font kerning (negative value means that letters are closer to each other) */
 $draw->setTextKerning(-8);
 /* Set font and font size used in PHP logo */
 $draw->setFont('Handel Gothic.ttf');
 $draw->setFontSize(150);
 /* Center text horizontally and vertically */
 $draw->setGravity(Imagick::GRAVITY_CENTER);
 /* Add center "php" with Y offset of -10 to canvas (inside ellipse) */
 $img->annotateImage($draw, 0, -10, 0, 'php');
 $img->setImageFormat('png');
 /* Set appropriate header for PNG and output the image */
 header('Content-Type: image/png');
 echo $img;
?>

The above example will output something similar to:

Imagick 类
ImagickDraw 类
ImagickPixel 类
ImagickPixelIterator 类

邮件相关扩展

数学扩展

非文本内容的MIME输出

进程控制扩展

其它基本扩展

其它服务

搜索引擎扩展

面向服务器的扩展

Session 扩展

文本处理

与变量和类型有关的扩展

Web Services

Windows 平台下的扩展

XML 操作

PHP 核心:Zend 引擎的黑客指南

序言

“counter” 扩展 - 一个连续的实例

counter.setup 安装/配置 counter.constants 预定义常量 counter.examples 范例 counter.counter-class Counter — Counter 类 counter.basic-interface Basic — 简单接口 counter.extended-interface Extended — 扩展接口

PHP 5 构建系统

buildsys.environment PHP 扩展开发构建 buildsys.skeleton ext_skel 脚本 buildsys.configunix 与 UNIX 构建系统交互: config.m4 buildsys.configwin 使用 Windows 构建系统:config.w32

扩展的结构

structure.files 组成扩展的文件 structure.basics Basic constructs structure.modstruct The zend_module structure structure.globals Extension globals structure.lifecycle Life cycle of an extension structure.tests Testing an extension

内存管理

memory.management 内存管理基础 memory.persistence 数据持久化 memory.TSRM 线程安全的资源管理器

变量的使用

variables.intro 介绍 variables.creating 创建变量并设置值

函数的编写

类和对象的使用

资源的使用

INI 设置的使用

流的使用

PDO 驱动

pdo.prerequisites 前提条件 pdo.preparation 配置与管理 pdo.implementing Fleshing out your skeleton pdo.building Building pdo.testing Testing pdo.packaging Packaging and distribution pdo.pdo-dbh-t pdo_dbh_t definition pdo.pdo-stmt-t pdo_stmt_t definition pdo.constants Constants pdo.error-handling Error handling

扩展相关 FAQ

Zend Engine 2 API 参考

Zend Engine 2 操作码列表

opcodes.list Opcode Descriptions and Examples

Zend Engine 1

ze1.intro 旧的介绍 ze1.streams Streams API for PHP Extension Authors ze1.zendapi Zend API:深入 PHP 内核 ze1.tsrm TSRM API

常见问题

一般信息

邮件列表

获取 PHP

数据库问题

安装 — 安装常见问题

编译问题

使用 PHP

Password Hashing — Safe Password Hashing

PHP 和 HTML

PHP 和 COM

PHP 和其它语言

从 PHP 4 移植到 PHP 5

杂类问题

附录

PHP 及其相关工程的历史

history.php PHP 的历史 history.php.related PHP 相关工程的历史 history.php.books PHP 相关书籍 history.php.publications PHP 相关文章

Migrating from PHP 5.4.x to PHP 5.5.x

migration55.changes What has changed in PHP 5.5.x migration55.incompatible Backward Incompatible Changes migration55.new-features New features migration55.deprecated Deprecated features in PHP 5.5.x migration55.changed-functions Changed Functions migration55.new-functions New Functions migration55.classes New Classes and Interfaces migration55.new-methods New Methods migration55.extensions-other Other changes to extensions migration55.global-constants New Global Constants migration55.ini Changes to INI file handling migration55.internals Changes to PHP Internals

Migrating from PHP 5.3.x to PHP 5.4.x

migration54.changes What has changed in PHP 5.4.x migration54.incompatible Backward Incompatible Changes migration54.new-features New features migration54.sapi Changes in SAPI modules migration54.deprecated Deprecated features in PHP 5.4.x migration54.parameters Changed Functions migration54.functions New Functions migration54.classes New Classes and Interfaces migration54.methods New Methods migration54.removed-extensions Removed Extensions migration54.extensions-other Other changes to extensions migration54.global-constants New Global Constants migration54.ini Changes to INI file handling migration54.other Other changes

从 PHP 5.2.x 移植到 PHP 5.3.x

migration53.changes PHP 5.3.x 的变化 migration53.incompatible 不向下兼容的变化 migration53.new-features 新特性 migration53.windows Windows 支持改变 migration53.sapi SAPI 模块的改变 migration53.deprecated PHP 5.3.x 中弃用的功能 migration53.undeprecated PHP 5.3.x 保留的功能 migration53.parameters 新参数 migration53.functions 新函数 migration53.new-stream-wrappers 新的流包装器 migration53.new-stream-filters 新的流过滤器 migration53.class-constants 新增的类常量 migration53.methods 新增的方法 migration53.new-extensions 新的扩展 migration53.removed-extensions 被移除的扩展 migration53.extensions-other Other changes to extensions migration53.classes 新类 migration53.global-constants 新的全局常量 migration53.ini INI 文件处理改变 migration53.other 其他改变

Migrating from PHP 5.1.x to PHP 5.2.x

migration52.changes What has changed in PHP 5.2.x migration52.incompatible Backward Incompatible Changes migration52.error-messages New Error Messages migration52.datetime Changes in PHP datetime

support

migration52.parameters New Parameters migration52.functions New Functions migration52.methods New Methods migration52.removed-extensions Removed Extensions migration52.new-extensions New Extensions migration52.classes New Classes migration52.global-constants New Global Constants migration52.class-constants New Class Constants migration52.newconf New INI Configuration Directives migration52.errorrep Error Reporting migration52.other Other Enhancements

Migrating from PHP 5.0.x to PHP 5.1.x

migration51.changes Key PHP 5.1.x features migration51.references Changes in reference handling migration51.reading Reading [] migration51.integer-parameters Integer values in function parameters migration51.oop Class and object changes migration51.extensions Extensions migration51.datetime Date/time support migration51.databases Changes in database support migration51.errorcheck Checking for E_STRICT

从 PHP 4 移植到 PHP 5

migration5.changes PHP 5 中有哪些改变 migration5.incompatible 未向下兼容的改变 migration5.cli-cgi CLI 和 CGI migration5.configuration 移植配置文件 migration5.functions 新函数 migration5.newconf 新指令 migration5.databases 数据库 migration5.oop 新对象模型 migrating5.errorrep 错误报告

类与对象(PHP 4)

keyword.class 类 keyword.extends 继承 oop4.constructor 构造函数 keyword.paamayim-nekudotayim 范围解析操作符(::) keyword.parent parent oop4.serialization 序列化对象 - 会话中的对象 oop4.magic-functions 魔术函数 __sleep 和 __wakeup oop4.newref 构造函数中的引用 oop4.object-comparison 对象的比较

PHP 的调试

debugger-about 关于调试器

配置选项

configure.about 核心配置选项列表

php.ini 配置

配置选项列表

可以在 php.ini 中使用下列配置选项对 PHP 进行配置。

“可修改范围”列决定了该配置选项在什么情况下可以被设置。 查看 可变配置选项 列表查看具体定义。

配置选项

名字 默认 可修改范围 更新日志
allow_call_time_pass_reference “1” PHP_INI_PERDIR 在 PHP 4.0.0 时是 PHP_INI_ALL 。 在 PHP 5.4.0 中移除该选项。
allow_url_fopen “1” PHP_INI_SYSTEM 在 PHP <= 4.3.4 时是 PHP_INI_ALL 。
allow_url_include “0” PHP_INI_ALL 在 PHP 5 时是 PHP_INI_SYSTEM。 从 PHP 5.2.0 起可用。
always_populate_raw_post_data “0” PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL 。 从 PHP 4.1.0 起可用。
apc.cache_by_default “1” PHP_INI_ALL 在 APC <= 3.0.12 时是 PHP_INI_SYSTEM。 从 APC 3.0.0 起可用。
apc.enabled “1” PHP_INI_SYSTEM 在 APC 2 时是 PHP_INI_SYSTEM。 在 APC <= 3.0.12 时是 PHP_INI_ALL 。
apc.enable_cli “0” PHP_INI_SYSTEM 从 APC 3.0.7 起可用。
apc.file_update_protection “2” PHP_INI_SYSTEM 从 APC 3.0.6 起可用。
apc.filters NULL PHP_INI_SYSTEM  
apc.gc_ttl “3600” PHP_INI_SYSTEM  
apc.include_once_override “0” PHP_INI_SYSTEM 从 APC 3.0.12 起可用。
apc.localcache “0” PHP_INI_SYSTEM 从 APC 3.0.14 起可用。
apc.localcache.size “512” PHP_INI_SYSTEM 从 APC 3.0.14 起可用。
apc.max_file_size “1M” PHP_INI_SYSTEM 从 APC 3.0.7 起可用。
apc.mmap_file_mask NULL PHP_INI_SYSTEM  
apc.num_files_hint “1000” PHP_INI_SYSTEM  
apc.optimization “0” PHP_INI_ALL 在 APC 2 时是 PHP_INI_SYSTEM。 在 APC 3.0.13 中移除该选项。
apc.report_autofilter “0” PHP_INI_SYSTEM 从 APC 3.0.11 起可用。
apc.rfc1867 “0” PHP_INI_SYSTEM 从 APC 3.0.13 起可用。
apc.rfc1867_freq “0” PHP_INI_SYSTEM  
apc.rfc1867_name “APC_UPLOAD_PROGRESS” PHP_INI_SYSTEM  
apc.rfc1867_prefix upload_ PHP_INI_SYSTEM  
apc.shm_segments “1” PHP_INI_SYSTEM  
apc.shm_size “30” PHP_INI_SYSTEM  
apc.slam_defense “0” PHP_INI_SYSTEM 从 APC 3.0.0 起可用。
apc.stat “1” PHP_INI_SYSTEM 从 APC 3.0.10 起可用。
apc.stat_ctime “0” PHP_INI_SYSTEM 从 APC 3.0.13 起可用。
apc.ttl “0” PHP_INI_SYSTEM 从 APC 3.0.0 起可用。
apc.user_entries_hint “4096” PHP_INI_SYSTEM 从 APC 3.0.0 起可用。
apc.user_ttl “0” PHP_INI_SYSTEM 从 APC 3.0.0 起可用。
apc.write_lock “1” PHP_INI_SYSTEM 从 APC 3.0.11 起可用。
apd.bitmask “0” PHP_INI_ALL 在 apd 0.9 中移除该选项。
apd.dumpdir NULL PHP_INI_ALL  
apd.statement_tracing “0” PHP_INI_ALL 从 apd 0.9 起可用。
arg_separator “&” PHP_INI_ALL 在 PHP 4.0.6 中移除该选项。
arg_separator.input “&” PHP_INI_PERDIR 从 PHP 4.0.5 起可用。
arg_separator.output “&” PHP_INI_ALL 从 PHP 4.0.5 起可用。
asp_tags “0” PHP_INI_PERDIR 在 PHP 4.0.0 时是 PHP_INI_ALL 。
assert.active “1” PHP_INI_ALL  
assert.bail “0” PHP_INI_ALL  
assert.callback NULL PHP_INI_ALL  
assert.quiet_eval “0” PHP_INI_ALL  
assert.warning “1” PHP_INI_ALL  
async_send “0” PHP_INI_ALL 从 PHP 4.2.0 起可用。 在 PHP 4.3.0 中移除该选项。
auto_append_file NULL PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL 。
auto_detect_line_endings “0” PHP_INI_ALL 从 PHP 4.3.0 起可用。
auto_globals_jit “1” PHP_INI_PERDIR 从 PHP 5.0.0 起可用。
auto_prepend_file NULL PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL 。
axis2.client_home “~/work/axisc/c/deply” PHP_INI_ALL  
axis2.enable_exception “1” PHP_INI_ALL  
axis2.enable_trace “1” PHP_INI_ALL  
axis2.log_path “/tmp” PHP_INI_ALL  
bcmath.scale “0” PHP_INI_ALL  
bcompiler.enabled “1” PHP_INI_ALL 从 bcompiler 0.8 起可用。
birdstep.max_links “-1” PHP_INI_ALL 从 PHP 4.2.0 起可用。
blenc.key_file “/usr/local/etc/blenckeys” PHP_INI_ALL  
browscap NULL PHP_INI_SYSTEM  
cgi.check_shebang_line “1” PHP_INI_SYSTEM 从 PHP 5.2.1 起可用。
cgi.discard_path “0” PHP_INI_SYSTEM 从 PHP 5.3.0 起可用。
cgi.fix_pathinfo “1” PHP_INI_SYSTEM 在 PHP <= 5.2.0 时是 PHP_INI_ALL 。 从 PHP 4.3.0 起可用。
cgi.force_redirect “1” PHP_INI_SYSTEM 在 PHP <= 5.2.0 时是 PHP_INI_ALL 。 从 PHP 4.2.0 起可用。
cgi.nph “0” PHP_INI_ALL 从 PHP 4.3.5 起可用。
cgi.redirect_status_env NULL PHP_INI_SYSTEM 在 PHP <= 5.2.0 时是 PHP_INI_ALL 。 从 PHP 4.2.0 起可用。
cgi.rfc2616_headers “0” PHP_INI_ALL 从 PHP 4.3.0 起可用。
child_terminate “0” PHP_INI_ALL 从 PHP 4.0.5 起可用。
cli.pager “” PHP_INI_ALL 从 PHP 5.4.0 起可用。
cli.prompt “\b \> “ PHP_INI_ALL 从 PHP 5.4.0 起可用。
cli_server.color “0” PHP_INI_ALL 从 PHP 5.4.0 起可用。
coin_acceptor.autoreset “On” PHP_INI_ALL 在 coin_acceptor 0.2 中移除该选项。
coin_acceptor.auto_initialize “Off” PHP_INI_ALL 从 coin_acceptor 0.2 起可用。
coin_acceptor.auto_reset “On” PHP_INI_ALL 从 coin_acceptor 0.2 起可用。
coin_acceptor.command_function “Off” PHP_INI_ALL 从 coin_acceptor 0.3 起可用。
coin_acceptor.delay “53132” PHP_INI_ALL 在 coin_acceptor 0.2 中移除该选项。
coin_acceptor.delay_coins “53132” PHP_INI_ALL 从 coin_acceptor 0.2 起可用。
coin_acceptor.delay_prom “55748” PHP_INI_ALL 从 coin_acceptor 0.2 起可用。
coin_acceptor.device “/dev/ttyS1” PHP_INI_ALL 在 coin_acceptor 0.2 中移除该选项。
coin_acceptor.lock_on_close “Off” PHP_INI_ALL 从 coin_acceptor 0.2 起可用。
coin_acceptor.start_unlocked “On” PHP_INI_ALL 从 coin_acceptor 0.2 起可用。
com.allow_dcom “0” PHP_INI_SYSTEM 从 PHP 4.0.5 起可用。
com.autoregister_casesensitive “1” PHP_INI_ALL 在 PHP 4 时是 PHP_INI_SYSTEM。从 PHP 4.1.0 起可用。
com.autoregister_typelib “0” PHP_INI_ALL 在 PHP 4 时是 PHP_INI_SYSTEM。 从 PHP 4.1.0 起可用。
com.autoregister_verbose “0” PHP_INI_ALL 在 PHP 4 时是 PHP_INI_SYSTEM。 从 PHP 4.1.0 起可用。
com.code_page “” PHP_INI_ALL 从 PHP 5.0.0 起可用。
com.typelib_file “” PHP_INI_SYSTEM 从 PHP 4.0.5 起可用。
crack.default_dictionary NULL PHP_INI_PERDIR 在 crack <= 0.2 时是 PHP_INI_SYSTEM。 从 PHP 4.0.5 起可用。 在 PHP 5.0.0 中移除该选项。
daffodildb.default_host “localhost” PHP_INI_ALL  
daffodildb.default_password “daffodil” PHP_INI_ALL  
daffodildb.default_socket NULL PHP_INI_ALL  
daffodildb.default_user “DAFFODIL” PHP_INI_ALL  
daffodildb.port “3456” PHP_INI_ALL  
date.default_latitude “31.7667” PHP_INI_ALL 从 PHP 5.0.0 起可用。
date.default_longitude “35.2333” PHP_INI_ALL 从 PHP 5.0.0 起可用。
date.sunrise_zenith “90.583333” PHP_INI_ALL 从 PHP 5.0.0 起可用。
date.sunset_zenith “90.583333” PHP_INI_ALL 从 PHP 5.0.0 起可用。
date.timezone “” PHP_INI_ALL 从 PHP 5.1.0 起可用。
dba.default_handler “” PHP_INI_ALL 从 PHP 4.3.3 起可用。
dbx.colnames_case “unchanged” PHP_INI_SYSTEM 从 PHP 4.3.0 起可用。 在 PHP 5.1.0 中移除该选项。
default_charset “” PHP_INI_ALL  
default_mimetype “text/html” PHP_INI_ALL  
default_socket_timeout “60” PHP_INI_ALL 从 PHP 4.3.0 起可用。
define_syslog_variables “0” PHP_INI_ALL 在 PHP 5.4.0 中移除该选项。
detect_unicode “1” PHP_INI_ALL 从 PHP 5.1.0 起可用。 此已废弃的 特性即将 被移除。
disable_classes “” php.ini only 从 PHP 4.3.2 起可用。
disable_functions “” php.ini only 从 PHP 4.0.1 起可用。
display_errors “1” PHP_INI_ALL  
display_startup_errors “0” PHP_INI_ALL 从 PHP 4.0.3 起可用。
docref_ext “” PHP_INI_ALL 从 PHP 4.3.2 起可用。
docref_root “” PHP_INI_ALL 从 PHP 4.3.0 起可用。
doc_root NULL PHP_INI_SYSTEM  
enable_dl “1” PHP_INI_SYSTEM 此已废弃的 特性即将 被移除。
engine “1” PHP_INI_ALL 从 PHP 4.0.5 起可用。
error_append_string NULL PHP_INI_ALL  
error_log NULL PHP_INI_ALL  
error_prepend_string NULL PHP_INI_ALL  
error_reporting NULL PHP_INI_ALL  
etpan.default.charset “utf-8” PHP_INI_ALL  
etpan.default.protocol “imap” PHP_INI_ALL  
exif.decode_jis_intel “JIS” PHP_INI_ALL 从 PHP 4.3.0 起可用。
exif.decode_jis_motorola “JIS” PHP_INI_ALL 从 PHP 4.3.0 起可用。
exif.decode_unicode_intel “UCS-2LE” PHP_INI_ALL 从 PHP 4.3.0 起可用。
exif.decode_unicode_motorola “UCS-2BE” PHP_INI_ALL 从 PHP 4.3.0 起可用。
exif.encode_jis “” PHP_INI_ALL 从 PHP 4.3.0 起可用。
exif.encode_unicode “ISO-8859-15” PHP_INI_ALL 从 PHP 4.3.0 起可用。
exit_on_timeout “” PHP_INI_ALL 从 PHP 5.3 起可用。0
expect.logfile “” PHP_INI_ALL  
expect.loguser “1” PHP_INI_ALL  
expect.timeout “10” PHP_INI_ALL  
expose_php “1” php.ini only  
extension NULL php.ini only  
extension_dir “/path/to/php” PHP_INI_SYSTEM  
fastcgi.impersonate “0” PHP_INI_SYSTEM 在 PHP <= 5.2.0 时是 PHP_INI_ALL 。 从 PHP 4.3.0 起可用。
fastcgi.logging “1” PHP_INI_SYSTEM 在 PHP <= 5.2.0 时是 PHP_INI_ALL 。 从 PHP 4.4.0 起可用。
fbsql.allow_persistant “1” PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。 在 PHP 4.2.0 中移除该选项。
fbsql.allow_persistent “1” PHP_INI_SYSTEM 从 PHP 4.2.0 起可用。
fbsql.autocommit “1” PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。
fbsql.batchSize “1000” PHP_INI_SYSTEM 从 PHP 4.2.0 起可用。 在 PHP 5.1.0 中移除该选项。
fbsql.batchsize “1000” PHP_INI_ALL 从 PHP 5.1.0 起可用。
fbsql.default_database “” PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。
fbsql.default_database_password “” PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。
fbsql.default_host NULL PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。
fbsql.default_password “” PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。
fbsql.default_user “_SYSTEM” PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。
fbsql.generate_warnings “0” PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。
fbsql.max_connections “128” PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。
fbsql.max_links “128” PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。
fbsql.max_persistent “-1” PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。
fbsql.max_results “128” PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。
fbsql.mbatchSize “1000” PHP_INI_SYSTEM 从 PHP 4.0.6 起可用。 在 PHP 4.2.0 中移除该选项。
fbsql.show_timestamp_decimals “0” PHP_INI_SYSTEM 从 PHP 5.1.5 起可用。
file_uploads “1” PHP_INI_SYSTEM 在 PHP <= 4.2.3 时是 PHP_INI_ALL 。 从 PHP 4.0.3 起可用。
filter.default “unsafe_raw” PHP_INI_PERDIR 在 filter <= 0.9.4 时是 PHP_INI_ALL 。 从 PHP 5.2.0 起可用。
filter.default_flags NULL PHP_INI_PERDIR 在 filter <= 0.9.4 时是 PHP_INI_ALL 。 从 PHP 5.2.0 起可用。
from “” PHP_INI_ALL  
gd.jpeg_ignore_warning “0” PHP_INI_ALL 从 PHP 5.1.3 起可用。
geoip.custom_directory NULL PHP_INI_ALL 从 geoip 1.0.1 起可用。
geoip.database_standard “GeoIP.dat” PHP_INI_ALL 在 geoip 1.0.1 中移除该选项。
gpc_order “GPC” PHP_INI_ALL 在 PHP 5.0.0 中移除该选项。
hidef.ini_path (char*)default_ini_path PHP_INI_SYSTEM  
highlight.bg “#FFFFFF” PHP_INI_ALL 在 PHP 5.4.0 中移除该选项。
highlight.comment “#FF8000” PHP_INI_ALL  
highlight.default “#0000BB” PHP_INI_ALL  
highlight.html “#000000” PHP_INI_ALL  
highlight.keyword “#007700” PHP_INI_ALL  
highlight.string “#DD0000” PHP_INI_ALL  
html_errors “1” PHP_INI_ALL 在 PHP <= 4.2.3 时是 PHP_INI_SYSTEM。 从 PHP 4.0.2 起可用。
htscanner.config_file ”.htaccess” PHP_INI_SYSTEM  
htscanner.default_docroot “/” PHP_INI_SYSTEM  
htscanner.default_ttl “300” PHP_INI_SYSTEM 从 htscanner 0.6.0 起可用。
htscanner.stop_on_error “0” PHP_INI_SYSTEM 从 htscanner 0.7.0 起可用。
http.allowed_methods “” PHP_INI_ALL Available since pecl_http 0.4.0. 在 pecl_http 1.0.0 中移除该选项。
http.allowed_methods_log “” PHP_INI_ALL Available since pecl_http 0.12.0. 在 pecl_http 1.0.0 中移除该选项。
http.cache_log “” PHP_INI_ALL Available since pecl_http 0.8.0. 在 pecl_http 1.0.0 中移除该选项。
http.composite_log “” PHP_INI_ALL Available since pecl_http 0.12.0. 在 pecl_http 1.0.0 中移除该选项。
http.etag.mode “MD5” PHP_INI_ALL 从 pecl_http 1.0.0 起可用。
http.etag_mode “MD5” PHP_INI_ALL Available since pecl_http 0.12.0. 在 pecl_http 1.0.0 中移除该选项。
http.force_exit “1” PHP_INI_ALL 从 pecl_http 0.18.0 起可用。
http.log.allowed_methods “” PHP_INI_ALL 从 pecl_http 1.0.0 起可用。
http.log.cache “” PHP_INI_ALL 从 pecl_http 1.0.0 起可用。
http.log.composite “” PHP_INI_ALL 从 pecl_http 1.0.0 起可用。
http.log.not_found “” PHP_INI_ALL 从 pecl_http 1.0.0 起可用。
http.log.redirect “” PHP_INI_ALL 从 pecl_http 1.0.0 起可用。
http.ob_deflate_auto “0” PHP_INI_PERDIR Available since pecl_http 0.21.0. 在 pecl_http 1.0.0 中移除该选项。
http.ob_deflate_flags “0” PHP_INI_ALL Available since pecl_http 0.21.0. 在 pecl_http 1.0.0 中移除该选项。
http.ob_inflate_auto “0” PHP_INI_PERDIR Available since pecl_http 0.21.0. 在 pecl_http 1.0.0 中移除该选项。
http.ob_inflate_flags “0” PHP_INI_ALL Available since pecl_http 0.21.0. 在 pecl_http 1.0.0 中移除该选项。
http.only_exceptions “0” PHP_INI_ALL 从 pecl_http 0.11.0 起可用。
http.persistent.handles.ident “GLOBAL” PHP_INI_ALL 从 pecl_http 1.5.0 起可用。
http.persistent.handles.limit “-1” PHP_INI_SYSTEM 从 pecl_http 1.5.0 起可用。
http.redirect_log “” PHP_INI_ALL Available since pecl_http 0.12.0. 在 pecl_http 1.0.0 中移除该选项。
http.request.datashare.connect “0” PHP_INI_SYSTEM 从 pecl_http 1.3.0 起可用。
http.request.datashare.cookie “0” PHP_INI_SYSTEM 从 pecl_http 1.3.0 起可用。
http.request.datashare.dns “1” PHP_INI_SYSTEM 从 pecl_http 1.3.0 起可用。
http.request.datashare.ssl “0” PHP_INI_SYSTEM 从 pecl_http 1.3.0 起可用。
http.request.methods.allowed “” PHP_INI_ALL 从 pecl_http 1.0.0 起可用。
http.request.methods.custom “” PHP_INI_PERDIR 从 pecl_http 1.0.0 起可用。
http.send.deflate.start_auto “0” PHP_INI_PERDIR 从 pecl_http 1.0.0 起可用。
http.send.deflate.start_flags “0” PHP_INI_ALL 从 pecl_http 1.0.0 起可用。
http.send.inflate.start_auto “0” PHP_INI_PERDIR 从 pecl_http 1.0.0 起可用。
http.send.inflate.start_flags “0” PHP_INI_ALL 从 pecl_http 1.0.0 起可用。
http.send.not_found_404 “1” PHP_INI_ALL 从 pecl_http 1.0.0 起可用。
hyerwave.allow_persistent “0” PHP_INI_SYSTEM 在 PHP 4.3.2 中移除该选项。
hyperwave.allow_persistent “0” PHP_INI_SYSTEM 从 PHP 4.3.2 起可用。 在 PHP 5.0.0 中移除该选项。
hyperwave.default_port “418” PHP_INI_ALL 在 PHP 5.0.0 中移除该选项。
ibase.allow_persistent “1” PHP_INI_SYSTEM  
ibase.dateformat “%Y-%m-%d” PHP_INI_ALL  
ibase.default_charset NULL PHP_INI_ALL 从 PHP 5.0.0 起可用。
ibase.default_db NULL PHP_INI_SYSTEM 从 PHP 5.0.0 起可用。
ibase.default_password NULL PHP_INI_ALL  
ibase.default_user NULL PHP_INI_ALL  
ibase.max_links “-1” PHP_INI_SYSTEM  
ibase.max_persistent “-1” PHP_INI_SYSTEM  
ibase.timeformat “%H:%M:%S” PHP_INI_ALL  
ibase.timestampformat “%Y-%m-%d %H:%M:%S” PHP_INI_ALL  
ibm_db2.binmode “1” PHP_INI_ALL  
ibm_db2.i5_allow_commit “0” PHP_INI_SYSTEM 从 ibm_db2 1.4.9 起可用。
ibm_db2.i5_dbcs_alloc “0” PHP_INI_SYSTEM 从 ibm_db2 1.5.0 起可用。
ibm_db2.instance_name NULL PHP_INI_SYSTEM 从 ibm_db2 1.0.2 起可用。
iconv.input_encoding “ISO-8859-1” PHP_INI_ALL 从 PHP 4.0.5 起可用。
iconv.internal_encoding “ISO-8859-1” PHP_INI_ALL 从 PHP 4.0.5 起可用。
iconv.output_encoding “ISO-8859-1” PHP_INI_ALL 从 PHP 4.0.5 起可用。
ifx.allow_persistent “1” PHP_INI_SYSTEM 在 PHP 5.2.1 中移除该选项。
ifx.blobinfile “1” PHP_INI_ALL 在 PHP 5.2.1 中移除该选项。
ifx.byteasvarchar “0” PHP_INI_ALL 在 PHP 5.2.1 中移除该选项。
ifx.charasvarchar “0” PHP_INI_ALL 在 PHP 5.2.1 中移除该选项。
ifx.default_host NULL PHP_INI_SYSTEM 在 PHP 5.2.1 中移除该选项。
ifx.default_password NULL PHP_INI_SYSTEM 在 PHP 5.2.1 中移除该选项。
ifx.default_user NULL PHP_INI_SYSTEM 在 PHP 5.2.1 中移除该选项。
ifx.max_links “-1” PHP_INI_SYSTEM 在 PHP 5.2.1 中移除该选项。
ifx.max_persistent “-1” PHP_INI_SYSTEM 在 PHP 5.2.1 中移除该选项。
ifx.nullformat “0” PHP_INI_ALL 在 PHP 5.2.1 中移除该选项。
ifx.textasvarchar “0” PHP_INI_ALL 在 PHP 5.2.1 中移除该选项。
ignore_repeated_errors “0” PHP_INI_ALL 从 PHP 4.3.0 起可用。
ignore_repeated_source “0” PHP_INI_ALL 从 PHP 4.3.0 起可用。
ignore_user_abort “0” PHP_INI_ALL  
imlib2.font_cache_max_size “524288” PHP_INI_ALL  
imlib2.font_path “/usr/share/php/fonts/” PHP_INI_ALL  
implicit_flush “0” PHP_INI_ALL 在 PHP <= 4.2.3 时是 PHP_INI_PERDIR。
include_path ”.;/path/to/php/pear” PHP_INI_ALL  
ingres.allow_persistent “1” PHP_INI_SYSTEM 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
ingres.array_index_start “1” PHP_INI_ALL 从 ingres 1.4.0 起可用。
ingres.blob_segment_length “4096” PHP_INI_ALL 从 ingres 1.2.0 起可用。
ingres.cursor_mode “0” PHP_INI_ALL 从 ingres 1.1 起可用。
ingres.default_database NULL PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
ingres.default_password NULL PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
ingres.default_user NULL PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
ingres.max_links “-1” PHP_INI_SYSTEM 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
ingres.max_persistent “-1” PHP_INI_SYSTEM 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
ingres.report_db_warnings “1” PHP_INI_ALL 从 ingres 1.1 起可用。
ingres.timeout “-1” PHP_INI_ALL 从 ingres 1.4.0 起可用。
ingres.trace_connect “0” PHP_INI_ALL 从 ingres 1.2.1 起可用。
ircg.control_user “nobody” PHP_INI_ALL 从 PHP 5.0.0 起可用。 在 PHP 5.1.0 中移除该选项。
ircg.keep_alive_interval “60” PHP_INI_ALL 从 PHP 5.0.0 起可用。 在 PHP 5.1.0 中移除该选项。
ircg.max_format_message_sets “12” PHP_INI_ALL 从 PHP 5.0.0 起可用。 在 PHP 5.1.0 中移除该选项。
ircg.shared_mem_size “6000000” PHP_INI_ALL 从 PHP 5.0.0 起可用。 在 PHP 5.1.0 中移除该选项。
ircg.work_dir “/tmp/ircg” PHP_INI_ALL 从 PHP 5.0.0 起可用。 在 PHP 5.1.0 中移除该选项。
last_modified “0” PHP_INI_ALL 从 PHP 4.0.5 起可用。
ldap.base_dn NULL PHP_INI_ALL 在 PHP 4.2.0 中移除该选项。
ldap.max_links “” PHP_INI_SYSTEM  
log.dbm_dir “” PHP_INI_ALL 在 PHP 4.0.1 中移除该选项。
log_errors “0” PHP_INI_ALL  
log_errors_max_len “1024” PHP_INI_ALL 从 PHP 4.3.0 起可用。
magic_quotes_gpc “1” PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL 。 从 PHP 5.3.0 起不推荐使用。 在 PHP 5.4.0 中移除该选项。
magic_quotes_runtime “0” PHP_INI_ALL 在 PHP 5.4.0 中移除该选项。
magic_quotes_sybase “0” PHP_INI_ALL 在 PHP 5.4.0 中移除该选项。
mail.add_x_header “0” PHP_INI_PERDIR 从 PHP 5.3.0 起可用。
mail.force_extra_parameters NULL php.ini only 从 PHP 5.0.0 起可用。
mail.log “” PHP_INI_ALL 从 PHP 5.3.0 起可用。
mailparse.def_charset “us-ascii” PHP_INI_ALL 从 PHP 4.1.0 起可用。 在 PHP 4.2.0 中移除该选项。
maxdb.default_db NULL PHP_INI_ALL  
maxdb.default_host NULL PHP_INI_ALL  
maxdb.default_pw NULL PHP_INI_ALL  
maxdb.default_user NULL PHP_INI_ALL  
maxdb.long_readlen “200” PHP_INI_ALL  
max_execution_time “30” PHP_INI_ALL  
max_input_nesting_level “64” PHP_INI_PERDIR 从 PHP 4.4 起可用。8 and PHP 5.2.3.
max_input_vars 1000 PHP_INI_PERDIR 从 PHP 5.3.9 起可用。
max_input_time “” PHP_INI_PERDIR 从 PHP 4.3.0 起可用。
mbstring.detect_order NULL PHP_INI_ALL 从 PHP 4.0.6 起可用。
mbstring.encoding_translation “0” PHP_INI_PERDIR 从 PHP 4.3.0 起可用。
mbstring.func_overload “0” PHP_INI_SYSTEM 在 PHP <= 4.2.3 时是 PHP_INI_SYSTEM;从 PHP 4.3 起可用于 PHP_INI_SYSTEM | PHP_INI_PERDIR 。 through 5.2.6. 从 PHP 4.2.0 起可用。
mbstring.http_input “pass” PHP_INI_ALL 从 PHP 4.0.6 起可用。
mbstring.http_output “pass” PHP_INI_ALL 从 PHP 4.0.6 起可用。
mbstring.internal_encoding NULL PHP_INI_ALL 从 PHP 4.0.6 起可用。
mbstring.language “neutral” PHP_INI_ALL 从 PHP 4.3.0 起可用;在 PHP <= 5.2.6 时是 PHP_INI_PERDIR 。
mbstring.script_encoding NULL PHP_INI_ALL 从 PHP 4.3.0 起可用。
mbstring.strict_detection “0” PHP_INI_ALL 从 PHP 5.1.2 起可用。
mbstring.substitute_character NULL PHP_INI_ALL 从 PHP 4.0.6 起可用。
mcrypt.algorithms_dir NULL PHP_INI_ALL 从 PHP 4.0.2 起可用。
mcrypt.modes_dir NULL PHP_INI_ALL 从 PHP 4.0.2 起可用。
memcache.allow_failover “1” PHP_INI_ALL 从 memcache 2.0.2 起可用。
memcache.chunk_size “8192” PHP_INI_ALL 从 memcache 2.0.2 起可用。
memcache.default_port “11211” PHP_INI_ALL 从 memcache 2.0.2 起可用。
memcache.hash_function “crc32” PHP_INI_ALL 从 memcache 2.2.0 起可用。
memcache.hash_strategy “standard” PHP_INI_ALL 从 memcache 2.2.0 起可用。
memcache.max_failover_attempts “20” PHP_INI_ALL 从 memcache 2.1.0 起可用。
memory_limit “128M” PHP_INI_ALL  
mime_magic.debug “0” PHP_INI_SYSTEM 从 PHP 5.0.0 起可用。
mime_magic.magicfile “/path/to/php/magic.mime” PHP_INI_SYSTEM 从 PHP 4.3.0 起可用。
msql.allow_persistent “1” PHP_INI_ALL  
msql.max_links “” PHP_INI_ALL  
msql.max_persistent “” PHP_INI_ALL  
mssql.allow_persistent “1” PHP_INI_SYSTEM  
mssql.batchsize “0” PHP_INI_ALL 从 PHP 4.0.4 起可用。
mssql.charset “” PHP_INI_ALL 从 PHP 5.1.2 起可用。
mssql.compatability_mode “0” PHP_INI_ALL  
mssql.connect_timeout “5” PHP_INI_ALL  
mssql.datetimeconvert “1” PHP_INI_ALL 从 PHP 4.2.0 起可用。
mssql.max_links “” PHP_INI_SYSTEM  
mssql.max_persistent “” PHP_INI_SYSTEM  
mssql.max_procs “” PHP_INI_ALL 从 PHP 4.3.0 起可用。
mssql.min_error_severity “10” PHP_INI_ALL  
mssql.min_message_severity “10” PHP_INI_ALL  
mssql.secure_connection “0” PHP_INI_SYSTEM 从 PHP 4.3.0 起可用。
mssql.textlimit “” PHP_INI_ALL  
mssql.textsize “” PHP_INI_ALL  
mssql.timeout “60” PHP_INI_ALL 从 PHP 4.1.0 起可用。
mysql.allow_persistent “1” PHP_INI_SYSTEM  
mysql.connect_timeout “60” PHP_INI_ALL 在 PHP <= 4.3.2 时是 PHP_INI_SYSTEM。 从 PHP 4.3.0 起可用。
mysql.default_host NULL PHP_INI_ALL  
mysql.default_password NULL PHP_INI_ALL  
mysql.default_port NULL PHP_INI_ALL  
mysql.default_socket NULL PHP_INI_ALL 从 PHP 4.0.1 起可用。
mysql.default_user NULL PHP_INI_ALL  
mysql.max_links “” PHP_INI_SYSTEM  
mysql.max_persistent “” PHP_INI_SYSTEM  
mysql.trace_mode “0” PHP_INI_ALL 从 PHP 4.3.0 起可用。
mysqli.default_host NULL PHP_INI_ALL 从 PHP 5.0.0 起可用。
mysqli.default_port “3306” PHP_INI_ALL 从 PHP 5.0.0 起可用。
mysqli.default_pw NULL PHP_INI_ALL 从 PHP 5.0.0 起可用。
mysqli.default_socket NULL PHP_INI_ALL 从 PHP 5.0.0 起可用。
mysqli.default_user NULL PHP_INI_ALL 从 PHP 5.0.0 起可用。
mysqli.max_links “” PHP_INI_SYSTEM 从 PHP 5.0.0 起可用。
mysqli.reconnect “0” PHP_INI_SYSTEM 从 PHP 5.0.0 起可用。
namazu.debugmode “0” PHP_INI_ALL  
namazu.lang NULL PHP_INI_ALL  
namazu.loggingmode “0” PHP_INI_ALL  
namazu.sortmethod NULL PHP_INI_ALL  
namazu.sortorder NULL PHP_INI_ALL  
nsapi.read_timeout “60” PHP_INI_ALL 从 PHP 4.3.3 起可用。
oci8.default_prefetch “10” PHP_INI_SYSTEM 从 PHP 5.1.2 起可用。
oci8.max_persistent “” PHP_INI_SYSTEM 从 PHP 5.1.2 起可用。
oci8.old_oci_close_semantics “0” PHP_INI_SYSTEM 从 PHP 5.1.2 起可用。
oci8.persistent_timeout “” PHP_INI_SYSTEM 从 PHP 5.1.2 起可用。
oci8.ping_interval “60” PHP_INI_SYSTEM 从 PHP 5.1.2 起可用。
oci8.privileged_connect “0” PHP_INI_SYSTEM 从 PHP 5.1.2 起可用。
oci8.statement_cache_size “20” PHP_INI_SYSTEM 从 PHP 5.1.2 起可用。
odbc.allow_persistent “1” PHP_INI_SYSTEM  
odbc.check_persistent “1” PHP_INI_SYSTEM  
odbc.defaultbinmode “1” PHP_INI_ALL  
odbc.defaultlrl “4096” PHP_INI_ALL  
odbc.default_db NULL PHP_INI_ALL  
odbc.default_pw NULL PHP_INI_ALL  
odbc.default_user NULL PHP_INI_ALL  
odbc.max_links “” PHP_INI_SYSTEM  
odbc.max_persistent “” PHP_INI_SYSTEM  
odbtp.datetime_format “object” PHP_INI_ALL  
odbtp.detach_default_queries “0” PHP_INI_ALL  
odbtp.guid_format “string” PHP_INI_ALL 从 odbtp 1.1.3 起可用。
odbtp.interface_file “/usr/local/share/odbtp.conf” PHP_INI_ALL  
odbtp.truncation_errors “1” PHP_INI_ALL  
opendirectory.default_separator “/” PHP_INI_ALL 在 opendirectory 0.2.2 中移除该选项。
opendirectory.max_refs “” PHP_INI_ALL  
opendirectory.separator “/” PHP_INI_ALL 从 opendirectory 0.2.2 起可用。
open_basedir NULL PHP_INI_ALL 在 PHP < 5.2.3 时是 PHP_INI_SYSTEM。
oracle.allow_persistent “” PHP_INI_ALL 在 PHP 5.1.0 中移除该选项。
oracle.max_links “” PHP_INI_ALL 在 PHP 5.1.0 中移除该选项。
oracle.max_persistent “” PHP_INI_ALL 在 PHP 5.1.0 中移除该选项。
output_buffering “0” PHP_INI_PERDIR  
output_handler NULL PHP_INI_PERDIR 从 PHP 4.0.4 起可用。
pam.servicename “php” PHP_INI_ALL  
pcre.backtrack_limit “1000000” PHP_INI_ALL 从 PHP 5.2.0 起可用。
pcre.recursion_limit “100000” PHP_INI_ALL 从 PHP 5.2.0 起可用。
pdo.dsn.*   php.ini only 从 PHP 5.1.0 起可用。
pdo_odbc.connection_pooling “strict” PHP_INI_ALL 从 PHP 5.1.0 起可用。
pdo_odbc.db2_instance_name NULL PHP_INI_SYSTEM 从 PHP 5.1.1 起可用。 此已废弃的 特性即将 被移除。
pfpro.defaulthost “test-payflow.verisign.com” PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
pfpro.defaultport “443” PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
pfpro.defaulttimeout “30” PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
pfpro.proxyaddress “” PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
pfpro.proxylogon “” PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
pfpro.proxypassword “” PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
pfpro.proxyport “” PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 5.1.0 中移除该选项。
pgsql.allow_persistent “1” PHP_INI_SYSTEM  
pgsql.auto_reset_persistent “0” PHP_INI_SYSTEM 从 PHP 4.2.0 起可用。
pgsql.ignore_notice “0” PHP_INI_ALL 从 PHP 4.3.0 起可用。
pgsql.log_notice “0” PHP_INI_ALL 从 PHP 4.3.0 起可用。
pgsql.max_links “” PHP_INI_SYSTEM  
pgsql.max_persistent “” PHP_INI_SYSTEM  
phar.extract_list “” PHP_INI_ALL 从 phar 1.1.0 起可用。
phar.readonly “1” PHP_INI_ALL  
phar.require_hash “1” PHP_INI_ALL  
enable_post_data_reading On PHP_INI_PERDIR 从 PHP 5.4.0 起可用。
post_max_size “8M” PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_SYSTEM。 从 PHP 4.0.3 起可用。
precision “14” PHP_INI_ALL  
printer.default_printer “” PHP_INI_ALL 从 PHP 4.0.6 起可用。 在 PHP 4.1.1 中移除该选项。
python.append_path “” PHP_INI_ALL  
python.prepend_path ”.” PHP_INI_ALL  
realpath_cache_size “16K” PHP_INI_SYSTEM 从 PHP 5.1.0 起可用。
realpath_cache_ttl “120” PHP_INI_SYSTEM 从 PHP 5.1.0 起可用。
register_argc_argv “1” PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL 。
register_globals “0” PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL 。 从 PHP 5.3.0 起不推荐使用。 在 PHP 5.4.0 中移除该选项。
register_long_arrays “1” PHP_INI_PERDIR 从 PHP 5.0.0 起可用。 从 PHP 5.3.0 起不推荐使用。在 PHP 5.4.0 中移除该选项。
report_memleaks “1” PHP_INI_ALL 从 PHP 4.3.0 起可用。
report_zend_debug “1” PHP_INI_ALL 从 PHP 5.0.0 起可用。
request_order “” PHP_INI_PERDIR 在 PHP 5.3.0 时增加
runkit.internal_override “0” PHP_INI_SYSTEM  
runkit.superglobal “” PHP_INI_PERDIR  
safe_mode “0” PHP_INI_SYSTEM 在 PHP 5.4.0 中移除该选项。
safe_mode_allowed_env_vars PHP_ PHP_INI_SYSTEM 在 PHP 5.4.0 中移除该选项。
safe_mode_exec_dir “” PHP_INI_SYSTEM 在 PHP 5.4.0 中移除该选项。
safe_mode_gid “0” PHP_INI_SYSTEM 从 PHP 4.1.0 起可用。 在 PHP 5.4.0 中移除该选项。
safe_mode_include_dir NULL PHP_INI_SYSTEM 从 PHP 4.1.0 起可用。 在 PHP 5.4.0 中移除该选项。
safe_mode_protected_env_vars “LD_LIBRARY_PATH” PHP_INI_SYSTEM 在 PHP 5.4.0 中移除该选项。
sendmail_from NULL PHP_INI_ALL  
sendmail_path “/usr/sbin/sendmail -t -i” PHP_INI_SYSTEM  
serialize_precision “17” PHP_INI_ALL 从 PHP 4.3.2 起可用。 Until PHP 5.3.5, the default value was 100.
session.auto_start “0” PHP_INI_ALL  
session.bug_compat_42 “1” PHP_INI_ALL 从 PHP 4.3.0 起可用。 在 PHP 5.4.0 中移除该选项。
session.bug_compat_warn “1” PHP_INI_ALL 从 PHP 4.3.0 起可用。 在 PHP 5.4.0 中移除该选项。
session.cache_expire “180” PHP_INI_ALL  
session.cache_limiter “nocache” PHP_INI_ALL  
session.cookie_domain “” PHP_INI_ALL  
session.cookie_httponly “” PHP_INI_ALL 从 PHP 5.2.0 起可用。
session.cookie_lifetime “0” PHP_INI_ALL  
session.cookie_path “/” PHP_INI_ALL  
session.cookie_secure “” PHP_INI_ALL 从 PHP 4.0.4 起可用。
session.entropy_file “” PHP_INI_ALL  
session.entropy_length “0” PHP_INI_ALL  
session.gc_dividend “100” PHP_INI_ALL 从 PHP 4.3.0 起可用。 在 PHP 4.3.2 中移除该选项。
session.gc_divisor “100” PHP_INI_ALL 从 PHP 4.3.2 起可用。
session.gc_maxlifetime “1440” PHP_INI_ALL  
session.gc_probability “1” PHP_INI_ALL  
session.hash_bits_per_character “4” PHP_INI_ALL 从 PHP 5.0.0 起可用。
session.hash_function “0” PHP_INI_ALL 从 PHP 5.0.0 起可用。
session.name “PHPSESSID” PHP_INI_ALL  
session.referer_check “” PHP_INI_ALL  
session.save_handler “files” PHP_INI_ALL  
session.save_path “” PHP_INI_ALL  
session.serialize_handler “php” PHP_INI_ALL  
session.use_cookies “1” PHP_INI_ALL  
session.use_only_cookies “1” PHP_INI_ALL 从 PHP 4.3.0 起可用。
session.use_trans_sid “0” PHP_INI_ALL 在 PHP <= 4.2.3 时是 PHP_INI_ALL 。 在 PHP < 5 时是 PHP_INI_PERDIR。 从 PHP 4.0.3 起可用。
session_pgsql.create_table “1” PHP_INI_SYSTEM  
session_pgsql.db “host=localhost dbname=php_session user=nobody” PHP_INI_SYSTEM  
session_pgsql.disable “0” PHP_INI_SYSTEM  
session_pgsql.failover_mode “0” PHP_INI_SYSTEM  
session_pgsql.gc_interval “3600” PHP_INI_SYSTEM  
session_pgsql.keep_expired “0” PHP_INI_SYSTEM  
session_pgsql.sem_file_name “/tmp/php_session_pgsql” PHP_INI_SYSTEM  
session_pgsql.serializable “0” PHP_INI_SYSTEM  
session_pgsql.short_circuit “0” PHP_INI_SYSTEM  
session_pgsql.use_app_vars “0” PHP_INI_SYSTEM  
session_pgsql.vacuum_interval “21600” PHP_INI_SYSTEM  
short_open_tag “1” PHP_INI_ALL 在 PHP 4.0.0 时是 PHP_INI_ALL 。 在 PHP < 5.3.0 时是 PHP_INI_PERDIR
simple_cvs.authMethod “0” PHP_INI_ALL  
simple_cvs.compressionLevel “0” PHP_INI_ALL  
simple_cvs.cvsRoot “0” PHP_INI_ALL  
simple_cvs.host “0” PHP_INI_ALL  
simple_cvs.moduleName “0” PHP_INI_ALL  
simple_cvs.userName “0” PHP_INI_ALL  
simple_cvs.workingDir “0” PHP_INI_ALL  
SMTP “localhost” PHP_INI_ALL  
smtp_port “25” PHP_INI_ALL 从 PHP 4.3.0 起可用。
soap.wsdl_cache “1” PHP_INI_ALL 从 PHP 5.1.5 起可用。
soap.wsdl_cache_dir “/tmp” PHP_INI_ALL 从 PHP 5.0.0 起可用。
soap.wsdl_cache_enabled “1” PHP_INI_ALL 从 PHP 5.0.0 起可用。
soap.wsdl_cache_limit “5” PHP_INI_ALL 从 PHP 5.1.5 起可用。
soap.wsdl_cache_ttl “86400” PHP_INI_ALL 从 PHP 5.0.0 起可用。
sql.safe_mode “0” PHP_INI_SYSTEM  
sqlite.assoc_case “0” PHP_INI_ALL 从 PHP 5.0.0 起可用。
sybase.allow_persistent “1” PHP_INI_ALL 在 PHP <= 4.0.2 时是 PHP_INI_ALL 。 在 PHP <= 4.0.3 时是 PHP_INI_SYSTEM。
sybase.hostname NULL PHP_INI_ALL 在 PHP 4.0.2 中移除该选项。
sybase.interface_file “” PHP_INI_ALL  
sybase.login_timeout “0” PHP_INI_ALL 在 PHP 4.0.2 中移除该选项。
sybase.max_links “” PHP_INI_ALL 在 PHP <= 4.0.2 时是 PHP_INI_ALL 。 在 PHP <= 4.0.3 时是 PHP_INI_SYSTEM。
sybase.max_persistent “” PHP_INI_ALL 在 PHP <= 4.0.2 时是 PHP_INI_ALL 。 在 PHP <= 4.0.3 时是 PHP_INI_SYSTEM。
sybase.min_client_severity “10” PHP_INI_ALL 在 PHP 4.0.2 中移除该选项。
sybase.min_error_severity “10” PHP_INI_ALL  
sybase.min_message_severity “10” PHP_INI_ALL  
sybase.min_server_severity “10” PHP_INI_ALL 在 PHP 4.0.2 中移除该选项。
sybase.timeout “0” PHP_INI_ALL 在 PHP 4.0.2 中移除该选项。
sybct.allow_persistent “1” PHP_INI_SYSTEM 在 PHP <= 4.0.2 时是 PHP_INI_ALL 。 从 PHP 4.0.2 起可用。 在 PHP 4.0.3 中移除该选项。
sybct.deadlock_retry_count “0” PHP_INI_ALL 从 PHP 4.3.0 起可用。
sybct.hostname NULL PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 4.0.3 中移除该选项。
sybct.login_timeout “” PHP_INI_ALL 从 PHP 4.0.2 起可用。
sybct.max_links “” PHP_INI_SYSTEM 在 PHP <= 4.0.2 时是 PHP_INI_ALL 。 从 PHP 4.0.2 起可用。 在 PHP 4.0.3 中移除该选项。
sybct.max_persistent “” PHP_INI_SYSTEM 在 PHP <= 4.0.2 时是 PHP_INI_ALL 。 从 PHP 4.0.2 起可用。 在 PHP 4.0.3 中移除该选项。
sybct.min_client_severity “10” PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 4.0.3 中移除该选项。
sybct.min_server_severity “10” PHP_INI_ALL 从 PHP 4.0.2 起可用。 在 PHP 4.0.3 中移除该选项。
sybct.packet_size “0” PHP_INI_ALL 从 PHP 4.3.5 起可用。
sybct.timeout “0” PHP_INI_ALL 从 PHP 4.0.2 起可用。
sysvshm.init_mem “10000” PHP_INI_ALL  
tidy.clean_output “0” php.ini only 在 PHP 5 时是 PHP_INI_PERDIR。 从 PHP 5.0.0 起可用。
tidy.default_config “” PHP_INI_SYSTEM 从 PHP 5.0.0 起可用。
track_errors “0” PHP_INI_ALL  
track_vars “1” PHP_INI_ALL 在 PHP 4.0.3 中移除该选项。
unserialize_callback_func NULL PHP_INI_ALL 从 PHP 4.2.0 起可用。
uploadprogress.file.filename_template “/tmp/upt_%s.txt” PHP_INI_ALL  
upload_max_filesize “2M” PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL 。
max_file_uploads 20 PHP_INI_SYSTEM 从 PHP 5.2.12 起可用。
upload_tmp_dir NULL PHP_INI_SYSTEM  
url_rewriter.tags “a=href,area=href,frame=src,form=,fieldset=”   PHP_INI_ALL 从 PHP 4.0.4 起可用。
user_agent NULL PHP_INI_ALL 从 PHP 4.3.0 起可用。
user_dir NULL PHP_INI_SYSTEM  
user_ini.cache_ttl “300” PHP_INI_SYSTEM 从 PHP 5.3.0 起可用。
user_ini.filename ”.user.ini” PHP_INI_SYSTEM 从 PHP 5.3.0 起可用。
valkyrie.auto_validate “0” PHP_INI_ALL  
valkyrie.config_path NULL PHP_INI_ALL  
variables_order “EGPCS” PHP_INI_PERDIR 在 PHP <= 5.0.5 时是 PHP_INI_ALL 。
velocis.max_links “” PHP_INI_ALL 在 PHP 4.2.0 中移除该选项。
vld.active “0” PHP_INI_SYSTEM  
vld.execute “1” PHP_INI_SYSTEM 从 vld 0.8.0 起可用。
vld.skip_append “0” PHP_INI_SYSTEM 从 vld 0.8.0 起可用。
vld.skip_prepend “0” PHP_INI_SYSTEM 从 vld 0.8.0 起可用。
windows_show_crt_warning “0” PHP_INI_ALL 从 PHP 5.4.0 起可用。
xbithack “0” PHP_INI_ALL 从 PHP 4.0.5 起可用。
xdebug.auto_profile “0” PHP_INI_ALL 在 Xdebug 2.0.0 中移除该选项。
xdebug.auto_profile_mode “0” PHP_INI_ALL 在 Xdebug 2.0.0 中移除该选项。
xdebug.auto_trace “0” PHP_INI_ALL  
xdebug.collect_includes “1” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.collect_params “0” PHP_INI_ALL  
xdebug.collect_return “0” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.collect_vars “0” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.default_enable “1” PHP_INI_ALL 在 Xdebug 1 时是 PHP_INI_SYSTEM。
xdebug.dump.COOKIE NULL PHP_INI_ALL  
xdebug.dump.ENV NULL PHP_INI_ALL  
xdebug.dump.FILES NULL PHP_INI_ALL  
xdebug.dump.GET NULL PHP_INI_ALL  
xdebug.dump.POST NULL PHP_INI_ALL  
xdebug.dump.REQUEST NULL PHP_INI_ALL  
xdebug.dump.SERVER NULL PHP_INI_ALL  
xdebug.dump.SESSION NULL PHP_INI_ALL  
xdebug.dump_globals “1” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.dump_once “1” PHP_INI_ALL  
xdebug.dump_undefined “0” PHP_INI_ALL  
xdebug.extended_info “1” PHP_INI_SYSTEM 从 Xdebug 2.0.0 起可用。
xdebug.idekey “” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.manual_url http://www.php.net PHP_INI_ALL  
xdebug.max_nesting_level “100” PHP_INI_ALL  
xdebug.output_dir “/tmp” PHP_INI_PERDIR 在 Xdebug <= 1.2.0 时是 PHP_INI_SYSTEM。 在 Xdebug 2.0.0 中移除该选项。
xdebug.profiler_aggregate “0” PHP_INI_PERDIR 从 Xdebug 2.0.0 起可用。
xdebug.profiler_append “0” PHP_INI_PERDIR 从 Xdebug 2.0.0 起可用。
xdebug.profiler_enable “0” PHP_INI_PERDIR 从 Xdebug 2.0.0 起可用。
xdebug.profiler_enable_trigger “0” PHP_INI_PERDIR 从 Xdebug 2.0.0 起可用。
xdebug.profiler_output_dir “/tmp” PHP_INI_PERDIR 从 Xdebug 2.0.0 起可用。
xdebug.profiler_output_name “cachegrind.out.%p” PHP_INI_PERDIR 从 Xdebug 2.0.0 起可用。
xdebug.remote_autostart “0” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.remote_enable “0” PHP_INI_PERDIR  
xdebug.remote_handler “dbgp” PHP_INI_ALL  
xdebug.remote_host “localhost” PHP_INI_ALL  
xdebug.remote_log “” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.remote_mode “req” PHP_INI_ALL  
xdebug.remote_port “9000” PHP_INI_ALL  
xdebug.show_exception_trace “0” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.show_local_vars “0” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.show_mem_delta “0” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.trace_format “0” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.trace_options “0” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.trace_output_dir “/tmp” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.trace_output_name “trace.%c” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.var_display_max_children “128” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.var_display_max_data “512” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xdebug.var_display_max_depth “3” PHP_INI_ALL 从 Xdebug 2.0.0 起可用。
xmlrpc_errors “0” PHP_INI_SYSTEM 从 PHP 4.1.0 起可用。
xmlrpc_error_number “0” PHP_INI_ALL 从 PHP 4.1.0 起可用。
xmms.path “/usr/bin/xmms” PHP_INI_ALL  
xmms.session “0” PHP_INI_ALL  
y2k_compliance “1” PHP_INI_ALL 在 PHP 5.4.0 中移除该选项。
yami.response.timeout “5” PHP_INI_ALL 从 yami 1.0.1 起可用。
yaz.keepalive “120” PHP_INI_ALL  
yaz.log_file NULL PHP_INI_ALL 从 PHP 4.3.0 起可用。 在 PHP 5.0.0 中移除该选项。
yaz.log_mask NULL PHP_INI_ALL 从 yaz 1.0.3 起可用。
yaz.max_links “100” PHP_INI_ALL 从 PHP 4.3.0 起可用。 在 PHP 5.0.0 中移除该选项。
zend.enable_gc “1” PHP_INI_ALL 从 PHP 5.3.0 起可用。
zend.multibyte “0” PHP_INI_PERDIR 从 PHP 5.4.0 起可用。
zend.script_encoding NULL PHP_INI_ALL 从 PHP 5.4 起可用。0
zend.signal_check “0” PHP_INI_SYSTEM 从 PHP 5.4 起可用。0
zend.ze1_compatibility_mode “0” PHP_INI_ALL 从 PHP 5.0.0 起可用。 在 PHP 5.3.0 中移除该选项。
zend_extension NULL php.ini only  
zend_extension_debug NULL php.ini only  
zend_extension_debug_ts NULL php.ini only  
zend_extension_ts NULL php.ini only  
zlib.output_compression “0” PHP_INI_ALL 从 PHP 4.0.5 起可用。
zlib.output_compression_level “” PHP_INI_ALL 从 PHP 4.3.0 起可用。
zlib.output_handler “” PHP_INI_ALL 从 PHP 4.3.0 起可用。

配置段列表

This list includes the php.ini sections you can set to configure your PHP setup on a per Host or Path basis. These sections are optional.

These sections don’t directly affect PHP. They are used to group other php.ini directives together and to get them to act upon a particular host or on a particular path.

These sections are used only in CGI/FastCGI mode and they can not set extension and zend_extension directives.

配置段

名字 可修改范围 更新日志
[HOST=] PHP_INI_SYSTEM 在 PHP 5.3.0 时增加。
[PATH=] PHP_INI_SYSTEM 在 PHP 5.3.0 时增加。

这是配置指令的简短说明。

[HOST=<host>] This section allows you to define a set of php.ini directives that will take effect on the named host.

Example #1 Activate full on-screen error reporting for dev. domain

[HOST=dev.site.com]
error_reporting = E_ALL
display_errors = On
[PATH=<path>]

This section allows you to define a set of php.ini directives that will take effect when a script runs from the named path.

Example #2 Add security script for protected areas

[PATH=/home/site/public/secure]
auto_prepend_file=security.php

核心配置选项说明

该列表只包含核心的 php.ini 配置选项。扩展的配置选项在各个扩展的文档页面分别被描述。有关 session 的选项可以在 sessions 页面找到。

Httpd 选项

Httpd 选项

名字 默认 可修改范围 更新日志
async_send “0” PHP_INI_ALL  
语言选项

语言和杂类配置选项

名字 默认 可修改范围 更新日志
short_open_tag “1” PHP_INI_ALL 在 PHP 4.0.0 时是 PHP_INI_ALL。 在 PHP < 5.3.0 时是 PHP_INI_PERDIR。
asp_tags “0” PHP_INI_PERDIR 在 PHP 4.0.0 时是 PHP_INI_ALL。
precision “14” PHP_INI_ALL  
serialize_precision “17” PHP_INI_ALL 从 PHP 4.3.2 起可用。在 PHP 5.3.5以前,默认值为 100
y2k_compliance “1” PHP_INI_ALL 在 PHP 5.4.0 中移除该选项。
allow_call_time_pass_reference “1” PHP_INI_PERDIR 在 PHP 4.0.0 时是 PHP_INI_ALL。 在 PHP 5.4.0 中移除该选项。
disable_functions “” php.ini only 从 PHP 4.0.1 起可用。
disable_classes “” php.ini only 从 PHP 4.3.2 起可用。
exit_on_timeout “” PHP_INI_ALL 从 PHP 5.3.0 起可用。
expose_php “1” php.ini only  
zend.multibyte “0” PHP_INI_ALL 从 PHP 5.4.0 起可用
zend.script_encoding NULL PHP_INI_ALL 从 PHP 5.4.0 起可用
zend.signal_check “0” PHP_INI_SYSTEM 从 PHP 5.4.0 起可用
zend.ze1_compatibility_mode “0” PHP_INI_ALL 从 PHP 5.0.0起可用。 在 PHP 5.3.0 中移除该选项
detect_unicode “1” PHP_INI_ALL 从 PHP 5.1.0起可用。 此已废弃的 特性即将 被移除。

这是配置指令的简短说明。

short_open_tag boolean

决定是否允许使用 PHP 代码开始标志的缩写形式(<? ?>)。如果要和 XML 结合使用 PHP,可以禁用此选项以便于嵌入使用 <?xml ?>。否则还可以通过 PHP 来输出,例如:<?php echo ‘<?xml version=”1.0”’; ?>。如果禁用了,必须使用 PHP 代码开始标志的完整形式(<?php ?>)。

注解

本指令也会影响到缩写形式 <?=,它和 <? echo 等价。使用此缩写需要 short_open_tag 的值为 On。 从 PHP 5.4.0 起, <?= 总是可用的。

asp_tags boolean

除了通常的 <?php ?> 标志之外还允许使用 ASP 风格的标志 <% %>。这也包括了输出变量值的缩写 <%= $value %>。更多信息见从 HTML 中分离一节。

precision integer

浮点数中显示有效数字的位数。

serialize_precision integer

The number of significant digits stored while serializing floating point numbers.

y2k_compliance boolean

强制 2000 年兼容(在不兼容的浏览器中会出问题)。

allow_call_time_pass_reference boolean

在函数调用时参数被按照引用传递时是否发出警告。此方法已不被赞成并在 PHP/Zend 未来的版本中很可能不再支持。鼓励使用的方法是在函数定义中指定哪些参数应该用引用传递。鼓励大家尝试关闭此选项并确保脚本能够正常运行,以确保该脚本也能在未来的版本中运行(每次使用此特性都会收到一条警告)。

在函数调用时通过引用传递参数是不推荐的,因为它影响到了代码的整洁。如果函数的参数没有声明作为引用传递,函数可以通过未写入文档的方法修改其参数。要避免其副作用,最好仅在函数声明时指定那个参数需要通过引用传递。

参见引用的解释。

Changelog for allow_call_time_pass_reference

版本 说明
5.4.0 从 PHP 中移除。
5.3.0 Emits an E_DEPRECATED level error.
5.0.0 Deprecated, and generates an E_COMPILE_WARNING level error.
expose_php boolean

决定是否暴露 PHP 被安装在服务器上(例如在 Web 服务器的信息头中加上其签名:X-Powered-By: PHP/5.3.7)。 The PHP logo guids are also exposed, thus appending them to the URL of a PHP enabled site will display the appropriate logo (e.g., » http://www.php.net/?=PHPE9568F34-D428-11d2-A769-00AA001ACF42). This also affects the output of phpinfo(), as when disabled, the PHP logo and credits information will not be displayed.

See also php_logo_guid() and phpcredits().

disable_functions string

本指令允许你基于安全原因禁止某些函数。接受逗号分隔的函数名列表作为参数。 disable_functions 不受安全模式的影响。 本指令只能设置在 php.ini 中。例如不能将其设置在 httpd.conf。

disable_classes string

本指令可以使你出于安全的理由禁用某些类。用逗号分隔类名。disable_classes 不受安全模式的影响。 本指令只能设置在 php.ini 中。例如不能将其设置在 httpd.conf。

注解

可用性说明

本指令自 PHP 4.3.2 起可用。

zend.ze1_compatibility_mode boolean

Enable compatibility mode with Zend Engine 1 (PHP 4). It affects the cloning, casting (objects with no properties cast to FALSE or 0), and comparing of objects. In this mode, objects are passed by value instead of reference by default.

See also the section titled Migrating from PHP 4 to PHP 5.

警告

This feature has been DEPRECATED and REMOVED as of PHP 5.3.0.

zend.multibyte boolean

Enables parsing of source files in multibyte encodings.

zend.script_encoding string

This value will be used unless a declare(encoding=...) directive appears at the top of the script.

zend.signal_check boolean

To check for replaced signal handlers on shutdown.

detect_unicode boolean

Check for BOM (Byte Order Mark) and see if the file contains valid multibyte characters. This detection is performed before processing of __halt_compiler(). Available only in Zend Multibyte mode.

exit_on_timeout boolean

This is an Apache1 mod_php-only directive that forces an Apache child to exit if a PHP execution timeout occurred. Such a timeout causes an internal longjmp() call in Apache1 which can leave some extensions in an inconsistent state. By terminating the process any outstanding locks or memory will be cleaned up.

Resource Limits

Resource Limits

名字 默认 可修改范围 更新日志
memory_limit “128M” PHP_INI_ALL “8M” before PHP 5.2.0, “16M” in PHP 5.2.0

这是配置指令的简短说明。

memory_limit integer

This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. Note that to have no memory limit, set this directive to -1.

Prior to PHP 5.2.1, in order to use this directive it had to be enabled at compile time by using –enable-memory-limit in the configure line. This compile-time flag was also required to define the functions memory_get_usage() and memory_get_peak_usage() prior to 5.2.1.

当使用 integer 时, 其值以字节来衡量。还可以使用在FAQ中描述的速记符。

参见

max_execution_time.

Performance Tuning

Performance Tuning

名字 默认 可修改范围 更新日志  
realpath_cache_size “16K” PHP_INI_SYSTEM 从 PHP 5.1.0 起可用。
realpath_cache_ttl “120” PHP_INI_SYSTEM 从 PHP 5.1.0 起可用。

这是配置指令的简短说明。

realpath_cache_size integer

Determines the size of the realpath cache to be used by PHP. This value should be increased on systems where PHP opens many files, to reflect the quantity of the file operations performed.

realpath_cache_ttl integer

Duration of time (in seconds) for which to cache realpath information for a given file or directory. For systems with rarely changing files, consider increasing the value.

Data Handling

Data Handling Configuration Options

名字 默认 可修改范围 更新日志
track_vars “On” PHP_INI_??  
arg_separator.output “&” PHP_INI_ALL 从 PHP 4.0.5 起可用。
arg_separator.input “&” PHP_INI_PERDIR 从 PHP 4.0.5 起可用。
variables_order “EGPCS” PHP_INI_PERDIR 在 PHP <= 5.0.5 时是 PHP_INI_ALL。
request_order “” PHP_INI_PERDIR 从 PHP 5.3.0 起可用
auto_globals_jit “1” PHP_INI_PERDIR 从 PHP 5.0.0 起可用。
register_globals “0” PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL。 在 PHP 5.4.0 中移除该选项。
register_argc_argv “1” PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL。
register_long_arrays “1” PHP_INI_PERDIR 从 PHP 5.0.0. Deprecated in PHP 5.3.0. Removed in PHP 5.4.0 起可用。
post_max_size “8M” PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_SYSTEM。 从 PHP 4.0.3 起可用。
gpc_order “GPC” PHP_INI_ALL  
auto_prepend_file NULL PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL。
auto_append_file NULL PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL。
default_mimetype “text/html” PHP_INI_ALL  
default_charset “” PHP_INI_ALL  
always_populate_raw_post_data “0” PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL。 从 PHP 4.1.0 起可用。
allow_webdav_methods “0” PHP_INI_PERDIR  

这是配置指令的简短说明。

track_vars boolean

If enabled, then Environment, GET, POST, Cookie, and Server variables can be found in the global associative arrays $_ENV, $_GET, $_POST, $_COOKIE, and $_SERVER.

Note that as of PHP 4.0.3, track_vars is always turned on.

arg_separator.output string

The separator used in PHP generated URLs to separate arguments.

arg_separator.input string

List of separator(s) used by PHP to parse input URLs into variables.

variables_order string

Sets the order of the EGPCS (Environment, Get, Post, Cookie, and Server) variable parsing. For example, if variables_order is set to “SP” then PHP will create the superglobals $_SERVER and $_POST, but not create $_ENV, $_GET, and $_COOKIE. Setting to “” means no superglobals will be set.

If the deprecated register_globals directive is on, then variables_order also configures the order the ENV, GET, POST, COOKIE and SERVER variables are populated in global scope. So for example if variables_order is set to “EGPCS”, register_globals is enabled, and both $_GET[‘action’] and $_POST[‘action’] are set, then $action will contain the value of $_POST[‘action’] as P comes after G in our example directive value.

警告

In both the CGI and FastCGI SAPIs, $_SERVER is also populated by values from the environment; S is always equivalent to ES regardless of the placement of E elsewhere in this directive.

注解

The content and order of $_REQUEST is also affected by this directive.

request_order string

This directive describes the order in which PHP registers GET, POST and Cookie variables into the _REQUEST array. Registration is done from left to right, newer values override older values.

If this directive is not set, variables_order is used for $_REQUEST contents.

Note that the default distribution php.ini files does not contain the ‘C’ for cookies, due to security concerns.

auto_globals_jit boolean

When enabled, the SERVER and ENV variables are created when they’re first used (Just In Time) instead of when the script starts. If these variables are not used within a script, having this directive on will result in a performance gain.

The PHP directives register_globals, register_long_arrays, and register_argc_argv must be disabled for this directive to have any affect. Since PHP 5.1.3 it is not necessary to have register_argc_argv disabled.

警告

Usage of SERVER and ENV variables is checked during the compile time so using them through e.g. variable variables will not cause their initialization.

register_globals boolean

Whether or not to register the EGPCS (Environment, GET, POST, Cookie, Server) variables as global variables.

As of » PHP 4.2.0, this directive defaults to off.

Please read the security chapter on Using register_globals for related information.

Please note that register_globals cannot be set at runtime ( ini_set()). Although, you can use .htaccess if your host allows it as described above. An example .htaccess entry: php_flag register_globals off.

注解

register_globals is affected by the variables_order directive.

警告

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

register_argc_argv boolean

Tells PHP whether to declare the argv & argc variables (that would contain the GET information). See also command line.

register_long_arrays boolean

Tells PHP whether or not to register the deprecated long $HTTP_*_VARS type predefined variables. When On (default), long predefined PHP variables like $HTTP_GET_VARS will be defined. If you’re not using them, it’s recommended to turn them off, for performance reasons. Instead, use the superglobal arrays, like $_GET. This directive became available in PHP 5.0.0.

警告

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

enable_post_data_reading boolean

Disabling this option causes $_POST and $_FILES not to be populated. The only way to read postdata will then be through the php://input stream wrapper. This can be useful to proxy requests or to process the POST data in a memory efficient fashion.

post_max_size integer

Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. If memory limit is enabled by your configure script, memory_limit also affects file uploading. Generally speaking, memory_limit should be larger than post_max_size. 当使用 integer 时, 其值以字节来衡量。还可以使用在FAQ中描述的速记符。 If the size of post data is greater than post_max_size, the $_POST and $_FILES superglobals are empty. This can be tracked in various ways, e.g. by passing the $_GET variable to the script processing the data, i.e. <form action=”edit.php?processed=1”>, and then checking if $_GET[‘processed’] is set.

注解

PHP allows shortcuts for bit values, including K (kilo), M (mega) and G (giga). PHP will do the conversions automatically if you use any of these. Be careful not to exceed the 32 bit signed integer limit (if you’re using 32bit versions) as it will cause your script to fail.

gpc_order string

Set the order of GET/POST/COOKIE variable parsing. The default setting of this directive is “GPC”. Setting this to “GP”, for example, will cause PHP to completely ignore cookies and to overwrite any GET method variables with POST-method variables of the same name.

注解

This option is not available in PHP 4. Use variables_order instead.

auto_prepend_file string

Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the require function, so include_path is used.

The special value none disables auto-prepending.

auto_append_file string

Specifies the name of a file that is automatically parsed after the main file. The file is included as if it was called with the require function, so include_path is used.

The special value none disables auto-appending.

注解

If the script is terminated with exit(), auto-append will not occur.

default_mimetype string
default_charset string

PHP always outputs a character encoding by default in the Content-type: header. To disable sending of the charset, simply set it to be empty.

always_populate_raw_post_data boolean

Always populate the $HTTP_RAW_POST_DATA containing the raw POST data. Otherwise, the variable is populated only with unrecognized MIME type of the data. However, the preferred method for accessing the raw POST data is php://input. $HTTP_RAW_POST_DATA is not available with enctype=”multipart/form-data”.

allow_webdav_methods boolean

Allow handling of WebDAV http requests within PHP scripts (eg. PROPFIND, PROPPATCH, MOVE, COPY, etc.). This directive does not exist as of PHP 4.3.2. If you want to get the post data of those requests, you have to set always_populate_raw_post_data as well.

参见

magic_quotes_gpc, magic_quotes_runtime, and magic_quotes_sybase.

Paths and Directories

Paths and Directories Configuration Options

名字 默认 可修改范围 更新日志
include_path ”.;/path/to/php/pear” PHP_INI_ALL  
open_basedir NULL PHP_INI_ALL PHP_INI_SYSTEM in PHP < 5.3.0
doc_root NULL PHP_INI_SYSTEM  
user_dir NULL PHP_INI_SYSTEM  
extension_dir “/path/to/php” PHP_INI_SYSTEM  
extension NULL php.ini only  
zend_extension NULL php.ini only  
zend_extension_debug NULL php.ini only  
zend_extension_debug_ts NULL php.ini only  
zend_extension_ts NULL php.ini only  
cgi.check_shebang_line “1” PHP_INI_SYSTEM 从 PHP 5.2.0 起可用。
cgi.fix_pathinfo “1” PHP_INI_SYSTEM 从 PHP 4.3.0. PHP_INI_ALL prior to PHP 5.2.1 起可用。
cgi.force_redirect “1” PHP_INI_SYSTEM 从 PHP 4.2.0. PHP_INI_ALL prior to PHP 5.2.1 起可用。
cgi.redirect_status_env NULL PHP_INI_SYSTEM 从 PHP 4.2.0. PHP_INI_ALL prior to PHP 5.2.1 起可用。
cgi.rfc2616_headers “0” PHP_INI_ALL 从 PHP 4.3.0 起可用。
fastcgi.impersonate “0” PHP_INI_SYSTEM 从 PHP 4.3.0. PHP_INI_ALL prior to PHP 5.2.1 起可用。
fastcgi.logging “1” PHP_INI_SYSTEM 从 PHP 4.3.0. PHP_INI_ALL prior to PHP 5.2.1 起可用。

这是配置指令的简短说明。

include_path string

Specifies a list of directories where the require, include, fopen(), file(), readfile() and file_get_contents() functions look for files. The format is like the system’s PATH environment variable: a list of directories separated with a colon in Unix or semicolon in Windows.

PHP considers each entry in the include path separately when looking for files to include. It will check the first path, and if it doesn’t find it, check the next path, until it either locates the included file or returns with a warning or an error. You may modify or set your include path at runtime using set_include_path().

Example #1 Unix include_path

include_path=".:/php/includes"

Example #2 Windows include_path

include_path=".;c:\php\includes"

Using a . in the include path allows for relative includes as it means the current directory. However, it is more efficient to explicitly use include ‘./file’ than having PHP always check the current directory for every include.

open_basedir string

将 PHP 所能打开的文件限制在指定的目录树,包括文件本身。本指令不受安全模式打开或者关闭的影响。

当一个脚本试图用例如 fopen() 或者 gzopen() 打开一个文件时,该文件的位置将被检查。当文件在指定的目录树之外时 PHP 将拒绝打开它。所有的符号连接都会被解析,所以不可能通过符号连接来避开此限制。

特殊值 . 指明脚本的工作目录将被作为基准目录。但这有些危险,因为脚本的工作目录可以轻易被 chdir() 而改变。

在 httpd.conf 文件中中,open_basedir 可以像其它任何配置选项一样用“php_admin_value open_basedir none”的方法关闭(例如某些虚拟主机中)。

在 Windows 中,用分号分隔目录。在任何其它系统中用冒号分隔目录。作为 Apache 模块时,父目录中的 open_basedir 路径自动被继承。

用 open_basedir 指定的限制实际上是前缀,不是目录名。也就是说“open_basedir = /dir/incl”也会允许访问“/dir/include”和“/dir/incls”,如果它们存在的话。如果要将访问限制在仅为指定的目录,用斜线结束路径名。例如:“open_basedir = /dir/incl/”。

注解

支持多个目录是 3.0.7 加入的。

默认是允许打开所有文件。

doc_root string

PHP’s “root directory” on the server. Only used if non-empty. If PHP is configured with 安全模式, no files outside this directory are served. If PHP was not compiled with FORCE_REDIRECT, you should set doc_root if you are running PHP as a CGI under any web server (other than IIS). The alternative is to use the cgi.force_redirect configuration below.

user_dir string

The base name of the directory used on a user’s home directory for PHP files, for example public_html .

extension_dir string

In what directory PHP should look for dynamically loadable extensions. See also: enable_dl, and dl().

extension string

Which dynamically loadable extensions to load when PHP starts up.

zend_extension string

Absolute path to dynamically loadable Zend extension (for example APD) to load when PHP starts up.

zend_extension_debug string

Variant of zend_extension for extensions compiled with debug info.

zend_extension_debug_ts string

Variant of zend_extension for extensions compiled with debug info and thread safety.

zend_extension_ts string

Variant of zend_extension for extensions compiled with thread safety.

cgi.check_shebang_line boolean

Controls whether CGI PHP checks for line starting with #! (shebang) at the top of the running script. This line might be needed if the script support running both as stand-alone script and via PHP CGI. PHP in CGI mode skips this line and ignores its content if this directive is turned on.

cgi.fix_pathinfo boolean

Provides real PATH_INFO/ PATH_TRANSLATED support for CGI. PHP’s previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok what PATH_INFO is. For more information on PATH_INFO, see the CGI specs. Setting this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting of zero causes PHP to behave as before. It is turned on by default. You should fix your scripts to use SCRIPT_FILENAME rather than PATH_TRANSLATED.

cgi.force_redirect boolean

cgi.force_redirect is necessary to provide security running PHP as a CGI under most web servers. Left undefined, PHP turns this on by default. You can turn it off at your own risk.

注解

Windows Users: When using IIS this option must be turned off. For OmniHTTPD or Xitami the same applies.

cgi.redirect_status_env string

If cgi.force_redirect is turned on, and you are not running under Apache or Netscape (iPlanet) web servers, you may need to set an environment variable name that PHP will look for to know it is OK to continue execution.

注解

Setting this variable may cause security issues, know what you are doing first.

cgi.rfc2616_headers int

Tells PHP what type of headers to use when sending HTTP response code. If it’s set 0, PHP sends a Status: header that is supported by Apache and other web servers. When this option is set to 1, PHP will send » RFC 2616 compliant headers. Leave it set to 0 unless you know what you’re doing.

fastcgi.impersonate string

FastCGI under IIS (on WINNT based OS) supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under. mod_fastcgi under Apache does not currently support this feature (03/17/2002) Set to 1 if running under IIS. Default is zero.

fastcgi.logging boolean

Turns on SAPI logging when using FastCGI. Default is to enable logging.

File Uploads

File Uploads Configuration Options

名字 默认 可修改范围 更新日志
file_uploads “1” PHP_INI_SYSTEM 在 PHP <= 4.2.3 时是 PHP_INI_ALL。 从 PHP 4.0.3 起可用。
upload_tmp_dir NULL PHP_INI_SYSTEM  
max_input_nesting_level 64 PHP_INI_PERDIR 从 PHP 5.3.9 起可用。
max_input_vars 1000 PHP_INI_PERDIR 从 PHP 5.3.9 起可用。
upload_max_filesize “2M” PHP_INI_PERDIR 在 PHP <= 4.2.3 时是 PHP_INI_ALL。
max_file_uploads 20 PHP_INI_SYSTEM 从 PHP 5.2.12 起可用。

这是配置指令的简短说明。

file_uploads boolean or integer

Whether or not to allow HTTP file uploads. See also the upload_max_filesize, upload_tmp_dir, and post_max_size directives.

当使用 integer 时, 其值以字节来衡量。还可以使用在FAQ中描述的速记符。

upload_tmp_dir string

The temporary directory used for storing files when doing file upload. Must be writable by whatever user PHP is running as. If not specified PHP will use the system’s default.

If the directory specified here is not writable, PHP falls back to the system default temporary directory. If open_basedir is on, then the system default directory must be allowed for an upload to succeed.

upload_max_filesize integer

The maximum size of an uploaded file.

当使用 integer 时, 其值以字节来衡量。还可以使用在FAQ中描述的速记符。

max_file_uploads integer

The maximum number of files allowed to be uploaded simultaneously. Starting with PHP 5.3.4, upload fields left blank on submission do not count towards this limit.

General SQL

General SQL Configuration Options

名字 默认 可修改范围 更新日志
sql.safe_mode “0” PHP_INI_SYSTEM  

这是配置指令的简短说明。

sql.safe_mode boolean

If turned on, database connect functions that specify default values will use those values in place of supplied arguments. For default values see connect function documentation for the relevant database.

Windows Specific

Windows Specific Configuration Options

名字 默认 可修改范围 更新日志
windows_show_crt_warning “0” PHP_INI_ALL 从 PHP 5.4.0 起可用。

这是配置指令的简短说明。

windows_show_crt_warning boolean

This directive shows the Windows CRT warnings when enabled. These warnings were displayed by default until PHP 5.4.0.

扩展库分类

extensions.alphabetical 按字母顺序 extensions.membership 按归属分 extensions.state 按状态分

函数别名列表

保留字列表

reserved.keywords 关键词列表 reserved.classes 预定义类 reserved.constants 预定义常量

资源类型列表

可用过滤器列表

filters.string 字符串过滤器 filters.convert 转换过滤器 filters.compression 压缩过滤器 filters.encryption 加密过滤器

所支持的套接字传输器(Socket Transports)列表

transports.inet Internet 领域:TCP,UDP,SSL 和 TLS transports.unix Unix 领域:Unix 和 UDG

PHP 类型比较表

解析器代号列表

Userland Naming Guide

userlandnaming.globalnamespace Global Namespace userlandnaming.rules Rules userlandnaming.tips Tips

关于本手册

about.formats 手册的格式 about.notes 关于用户注释 about.prototypes 如何阅读函数的定义(函数原型) about.phpversions 本手册中所涉及的 PHP 版本 about.more 如何得到关于 PHP 更多的信息 about.howtohelp 如何帮助改进本文档 about.generate 如何生成手册的各种格式 about.translations 手册译文

Creative Commons Attribution 3.0

索引

indexes.functions 函数和方法列表 indexes.examples 示例列表

Changelog

待办事项

待处理

研究ptrace

(The 原始记录 is located in /home/docs/checkouts/readthedocs.org/user_builds/php-manual/checkouts/latest/install/fpm/index.rst, line 24.)

参考

文档翻译自: PHP Manual

参考中文译本: PHP 手册

引用文件

Git访问

If you wish to get the latest PHP source tree, you can obtain it through Git. You should be warned that the Git version is a development version, and as such, is often unstable, and may not even compile properly. The advantage of using Git, though, is that you can get the latest fixes and updates, without having to wait for the official releases.

PHP uses an advanced configuration system that requires you to have the following tools. re2c is only necessary for developers and can be found here. All other utilities can be obtained from the GNU FTP site.

autoconf: 2.13 (2.59+ for PHP 5.4+) automake: 1.4+ libtool: 1.4.x+ (except 1.4.2) bison: 1.28, 1.35, 1.75, 2.0 or higher flex (PHP 5.2 and earlier): 2.5.4 (not higher) re2c: 0.13.4+ If you’re experiencing problems, see also the section on buildconf failures.

通过Git使用PHP的步骤

You can retrieve the PHP source code from our GitHub mirror with this command:

git clone https://github.com/php/php-src.git

Alternatively, you can retrieve the source code from git.php.net with this command:

git clone http://git.php.net/repository/php-src.git

Make sure you’re in the right directory to work on PHP:

cd php-src

You can then check out the branch you want to build:

PHP 5.3: git checkout PHP-5.3 PHP 5.4: git checkout PHP-5.4 PHP HEAD: git checkout master

Note that certain combinations of autoconf, automake and libtool may not work when used together. See below for details. Also, certain versions of autoconf may generate warnings of AC_PROG_CPP called before AC_PROG_CC. These messages can usually be ignored.

Run ./buildconf to generate the configure script. This may take several moments. From this point onwards, installation is similar to the installation of one of the official packages with one main difference – you may need bison 1.28 or later and flex 2.5.4 (PHP 5.2 and earlier) or re2c 0.13.4+ or later (PHP 5.3 and later) to compile, because the pre-generated scanner and parser files may not be included in Git. There are many other things, such as the XML source code for the documentation, available via Git. See the web-based view of the Git server to see what is available.

The PHP Wiki has a useful Git FAQ, which provides useful tips and cheatsheets for using the PHP Git repository, and if you want to become involved in developing PHP, the Git Workflow page is also likely to be of interest.

PHP 手册

The PHP manual is still currently hosted on SVN, although it will be migrated to Git in the near future. To checkout the latest English version of the PHP manual: svn checkout https://svn.php.net/repository/phpdoc/modules/doc-en ./phpdoc-en

You can also check the SVN FAQ on the wiki.

autoconf, automake 和 libtool 信息

There seem to be problems with libtool 1.4.2. It is suggested that you use libtool 1.4, along with autoconf 2.13 and automake 1.4. You should also ensure that autoconf, automake and libtool are installed in the same directory. libtool 1.5 will not work.

The following combinations are known to work with PHP 5.3 and below:

autoconf 2.13, automake 1.4 and libtool 1.4.3 autoconf 2.13, automake 1.5 and libtool 1.4.3 If you have multiple versions of autoconf installed on your computer, as is common for many UNIXes, you can set the PHP_AUTOCONF and PHP_AUTOHEADER variables when running buildconf to indicate which versions it should use e.g.: PHP_AUTOCONF=autoconf213 PHP_AUTOHEADER=autoheader213 ./buildconf

Zend/zend_language_scanner.c: 没有这个文件或目录

PHP only supports flex 2.5.4, not later versions as they broke backwards compatibility. Please note that PHP 5.3 and later do not require flex at all.

在MongoDB/PHP里添加元数据到文件里

文件源

As a quick followup to the last blog, I was asked to demonstrate how we could include some metadata with a file during or after upload.

This is a great feature since we can retrieve all the information attached with a document during a query. Including metadata (i.e. comments, dates, votes or WHATEVER ELSE YOU LIKE) is just as easy.

We are going to pick up the ball at the point where you’ve got all your MongoDB objects ready:

<?php
 $date = new MongoDate();
 //使用 $set 添加元数据到文件
 $metaData = array('$set' => array(“comment”=>”MongoDB is awesome”, “date”=>$date));
 //设置搜索条件
 $criteria = array('_id' => $id);
 //更新文件的一些信息
 $db->grid->update($criteria, $metaData);
?>

Did you break a sweat? Probably not.

BTW, I threw in a little extra tidbit there with MongoDate(). It’s a better way of inputting a date into Mongo instead of using PHP date with a bunch of formatting to get it just right.

MongoDB和PHP – GridFS快速浏览

文件源

I’ve been tweeting quite a bit about MongoDB over the past few weeks and its time to blog.

About 2 months ago we decided to install and mess around with MongoDB. We went from messing around to serious adoption about 2 weeks ago when we realized the power of working with it and PHP. It was Mitch Pirtle of www.spacemonkeylabs.com that first pointed us in this direction. Mitch was very enthusiastic about Mongo as he explained the great potential. Yet, it was only until I added an array of data from PHP into Mongo that my eyes started to open up.

Go ahead, open another tab in your browser (KEEPING THIS ONE OPEN) and Google MongoDB if you haven’t already (I made it easy providing the link). You’ll find sufficient documentation to give you the warm and fuzzy that 10gen isn’t messing around. They are in the database game for the long haul.

During our play with MongoDB we realized how true the term NoSQL is. For all you SQL grease monkeys out there it’s liberating. No Joins, No Select, just plain NoSQL.

As an example, let’s start off with putting uploaded files “directly” into MongoDB via GridFS (the storage specification for handling large files). Here is how simple it is:

First, we are going to assume you already have the code in place to handle the upload itself. We first tested this using SWFUpload which provides quite a bit of flexibility if you like to control how your page looks during upload. From a PHP perspective, the uploaded file will be accessible via the predefined variable $_FILES.

这些是你上传文件到MongoDB必须做的:

<?php
 $m = new Mongo(); //connect
 $db = $m->selectDB("example"); //选择Mongo库
 $grid = $db->getGridFS(); //使用GridFS类来操作文件
 $name = $_FILES['Filedata']['name']; //可选择的 - 抓取上传文件名
 $id = $grid->storeUpload('Filedata',$name) //载入文件到MongoDB
?>

Yep, that was it. One thing that took me a “second” to realize is that you actually pass the literal name of the file_post_name (in the example ‘Filedata’) to MongoDB. It does all the heavy lifting of getting the data from the system and storing it. Also, take note that you get an $id back which is the MongoID that acts as the “primary key”. That makes it easy for you to reference the file right away if you need to.

So that’s a rather quick look and tip for MongoDB. Stay tuned as we continue to put out our MongoDB tricks and tips for PHP. We’re in it for the long haul too.