寫在前面
從PHP5.2.x遷移到PHP5.3.x,這是官方提供的Migrating from PHP 5.2.x to PHP 5.3.x的翻譯。還未完成。 文章參考了此文的翻譯http://www.flyinghail.net/?p=99 在此表示感謝。
翻譯追求表意,由于部分函數/類沒有使用經驗,翻譯出錯難免,請大家指正以修改、完善。
目錄
一、PHP 5.3.x中發生了什么變化
二、向后不兼容的變化
三、新功能
四、Windows支持的變化
五、SAPI modules中的變化
六、PHP 5.3.x中不建議使用的功能
七、PHP 5.3.x中去除不推薦的功能
八、新參數
九、新函數
十、新的stream wrappers
十一、新的類常量
十二、新方法
十三、新擴展
十四、移除的擴展
十五、擴展中的其他變化
十六、新的類
十七、新的全局常量
十八、INI文件handling的變化
十九、其他變化
一、PHP 5.3.x中發生了什么變化
PHP 5.3.x中絕大多數的改良對現有代碼無影響。但是需要考慮一小部分不兼容和新功能,并且在生產環境中切換PHP版本需要做下test。
從更舊的版本升級到php5.3.x,相關文檔如下
Upgrade Notes for PHP 5.2.x.
Upgrade Notes for PHP 5.1.x.
Migrating from PHP 4 to PHP 5.
二、向后不兼容的變化
盡管絕大多數PHP5代碼不需修改即可運行,但是請留意一些向后不兼容的變化:
所有PHP5.3.X附帶的extension使用了新的參數解析API,如果傳入不兼容的參數將導致函數返回NULL。
有部分例外情況,例如get_class()在發生錯誤的時候繼續返回FALSE
clearstatcache()默認不再清除realpath的緩存
realpath()現在完全獨立于操作系統,意味著例如__FILE__ . "/../x"這樣的無效相對路徑將不能再運行。
call_user_func() 這一系的函數現在可以使用 $this ,含父類。
array相關函數:natsort(), natcasesort(), usort(), uasort(), uksort(), array_flip(), 和 array_unique()不再接受object類型的參數
如果要使用,請先把object轉換為數組。
之前參數為引用的函數接受直接的值,現在則會產生一個fatal error。
任何之前參數直接傳常量或者字符的,需要先賦值到一個變量再調用函數。
舉例
function test(&$a) {
echo 'OK';
}
test('a');
PHP5.3.X中將導致一個fatal error
新的mysqlnd函數庫必須使用新的MySQL4.1的41字節的密碼。使用16字節的舊密碼將導致mysql_connect()和類似函數產生"mysqlnd cannot connect to MySQL 4.1+ using old authentication."的錯誤信息。
和libmysql一樣,新的mysqlnd函數庫不會讀取mysql配置文件(my.cnf/my.ini)
如果你的代碼依賴于mysql的配置文件,你可以用mysqli_options()函數加載。
注意,這意味著如果PDO MYSQL兼容mysqlnd則PDO::MYSQL_ATTR_READ_DEFAULT_FILE 和 PDO::MYSQL_ATTR_READ_DEFAULT_GROUP不會被defined。
SplFileInfo和其他目錄相關的類返回的路徑字符結尾處的"/"將被移除。
__toString魔術方法不再接受參數
__get, __set, __isset, __unset, 和 __call必須使用public并且不能再定義為靜態方法
魔術方法__call現在能調用private和protected方法。
函數內include或者require一個文件,文件內將不能使用func_get_arg(), func_get_args() 和 func_num_args()函數。
以下關鍵詞成為保留關鍵詞,不能以其為其他函數、類命名。
goto
namespace
三、新功能
PHP 5.3.0提供了大量新功能
增加命名空間(namespaces)的支持
對遲靜態綁定(Late static binding)的支持
對跳轉標簽的支持(即有限的goto)
增加對閉包Closures(Lambda/匿名函數)的支持
新的魔術方法:__callStatic 和 __invoke.
支持 Nowdoc 語法,類似于加上單引號的Heredoc 語法。
現在可以將 Heredocs 用來初始化靜態變量與類中成員和常量
作為新增的Nowdoc語法的補充,現在可以使用雙引號來聲明。
可以在類以外使用const定義常量。
三元運算符現在可以使用簡寫 ?:
現在HTTP狀態200至399都被HTTP stream wrapper認為是成功的。
現在能夠動態訪問靜態方法
異常處理可以嵌套使用
默認開啟新的垃圾回收器以解決循環引用(circular references)問題。
mail()函數支持日志記錄(僅記錄使用這個函數發送的郵件)
四、為支持 Windows 所做的修改
與windows有關的修改
支持的最低Windows 版本是Windows XP SP3;Windows 2000; Windows 98, ME 和 NT4 不再支持。
Windows 二進制包不再支持i386 和 i486 。
實驗性的64位版本的PHP 。
編譯器支持VC++9(VS2008)
同時Snapshots和releases支持VC9. 使用 VC6 編譯的二進制包依舊被支持、與VC9同步發行。
PDO_OCI使用Oracle 10 或 11 客戶端庫的 php_pdo_oci.dll取代 php_pdo_oci8.dll 庫 (注意沒有 ‘8′) 。
依然支持連接數據庫的其他版本。
新php_oci8_11g.dll作為php_oci8.dll 的補充。
這兩個庫都只能開啟其中一個。php_oci8.dll 使用 Oracle 10.2 客戶端庫。
php_oci8_11g.dll 使用 Oracle 11 客戶端庫。
以下函數已經能夠支持windows
checkdnsrr()
dns_get_record()
fnmatch()
getmxrr()
getopt()
imagecolorclosesthwb()
inet_ntop()
inet_pton()
link()
linkinfo()
mcrypt_create_iv()
readlink()
socket_create_pair() - 之前這個函數能在 Windows 下用,但是因為bug被PHP4.3.0屏蔽。
stream_socket_pair()
symlink()
time_nanosleep()
time_sleep_until()
Other changes:
其他改變:
改良了 stat(), touch(), filemtime(), filesize() 和其他有關函數的可移植性。
現在可以在 Windows 下使用 link() 函數建立硬連接(hard links),使用 symlink() 建立符號連接(symbolic links)。
硬鏈接用于 Windows 2000,符號連接用于 Windows Vista.
Windows版PHP現在公布了一組以PHP_WINDOWS_*為前綴的新常量。
有關的常量列表和用途請查閱 Predefined Constants(預定義常量)。
Warning
警告
已放棄對ISAPI模塊的支持,可使用改進過的FastCGI SAPI模塊代替。
提示: 現已為windows上的PHP創建全新的網站, 含各版本的下載、發布候選、快照。
網址:http://windows.php.net/
五、SAPI 模塊中的改變
一個名為litespeed的SAPI模塊已經能夠使用
FastCGI現在總是開啟的并不能被關閉。請查看 sapi/cgi/CHANGES 獲得更多的信息。
CGI SAPI增加一個新選項 -T,用于測試腳本的重復執行時間。
CGI/FastCGI 現在支持.htaccess 風格的、用戶定義的 php.ini文件
默認禁用dl()函數,并且僅能夠在CLI, CGI 和embed SAPIs中使用。
六、PHP 5.3.x 中不建議使用的功能
PHP 5.3.0 引入了兩個新的錯誤級別:E_DEPRECATED和E_USER_DEPRECATED。
E_DEPRECATED表明不建議使用的函數或功能。
E_USER_DEPRECATED表明用戶代碼中不建議使用的功能,類似于E_USER_ERROR和E_USER_WARNING。
以下是不建議使用的INI選項。會導致啟動時拋出E_DEPRECATED錯誤。
define_syslog_variables
register_globals
register_long_arrays
safe_mode
magic_quotes_gpc
magic_quotes_runtime
magic_quotes_sybase
不建議用'#'在INI文件作注釋
不建議使用的函數:
call_user_method() (使用 call_user_func() 代替)
call_user_method_array() (使用 call_user_func_array() 代替)
define_syslog_variables()
dl()
ereg() (使用preg_match() 代替)
ereg_replace() (使用 preg_replace() 代替)
eregi() (使用 preg_match() 結合 ‘i’ 修飾符以代替)
eregi_replace() (使用 preg_replace() 結合 ‘i’ 修飾符以代替)
set_magic_quotes_runtime() 和它的別名 magic_quotes_runtime()
session_register() (使用 $_SESSION 超全局變量(superglobal)代替)
session_unregister() (使用 $_SESSION 超全局變量(superglobal)代替)
session_is_registered() (使用 $_SESSION 超全局變量(superglobal)代替)
set_socket_blocking() (使用 stream_set_blocking() 代替)
split() (使用 preg_split()代替)
spliti() (使用 preg_split()以修飾符'i'代替)
sql_regcase()
mysql_db_query() (使用 mysql_select_db() 和 mysql_query() 代替)
mysql_escape_string() (使用 mysql_real_escape_string() 代替)
使用LC_*系列常量代替字符串,來設置locale category names
The is_dst parameter to mktime(). Use the new timezone handling functions instead.
mktime()的參數is_dst 。用新的timezone處理函數代替。
不建議使用的功能:
不推薦將new的返回值為引用。
不推薦Call-time pass-by-reference 即不推薦func(&$param);
不推薦使用{}訪問string offsets。請使用 [] 代替。
七、PHP 5.3.x 恢復正常使用的功能
由于is_a()的普遍需求,使用它不再產生 E_STRICT 錯誤。
八、新的參數
在 PHP 5.3 中部分函數提供了新的可選參數:
PHP 核心:
clearstatcache() – 增加了 clear_realpath_cache 和 filename .
copy() – 增加數據流環境參數(stream context parameter), context .
fgetcsv() – 增加 escape .
ini_get_all() – 增加 details .
mail() 函數現在支持記錄發送的郵件。(僅對通過該函數發送的郵件有效)
nl2br() – 增加 is_xhtml .
parse_ini_file() – 增加 scanner_mode .
round() – 增加 mode .(PS:現在不光是四舍五入這一種形式了)
stream_context_create() – 增加 params .
strstr() 和 stristr() – 增加 before_needle .(PS:可以取指定字符前面的部分了)
json:
json_encode() – 增加 options .
json_decode() – 增加 depth .
Streams:
stream_select(), stream_set_blocking(), stream_set_timeout() 和 stream_set_write_buffer() 現在可以利用用戶空間的數據流封裝(user-space stream wrappers)。
sybase_ct:
sybase_connect() – 增加 new .
PHP 5.3.0中的新方法:
PHP 核心:
Exception::__construct() - 增加 previous.
九、新函數
PHP 核心:
array_replace() – 替換傳入的數組為一個數組。
array_replace_recursive() – 遞歸的替換數組中的元素。
class_alias() – 為用戶定義的類建立一個別名。
forward_static_call() – 在方法內(method context)執行用戶函數。
forward_static_call_array() – 在方法內(method context)執行用戶函數,參數使用數組。
gc_collect_cycles() – 強制收集已存在的垃圾回收數據(garbage cycles)。
gc_disable() – 關閉回收引用收集器(the circular reference collector)。
gc_enable() – 激活回收引用收集器(the circular reference collector)。
gc_enabled() – 返回回收引用收集器(the circular reference collector)的狀態。
get_called_class() – 返回執行靜態方法的類名。
gethostname() – 返回本地服務器當前的主機名(host name)。
header_remove() – 刪除之前使用 header() 函數設置的 HTTP 頭信息(HTTP header)。
lcfirst() – 將字符串第一個字符轉換成小寫。
parse_ini_string() – 解析配置字符串。
quoted_printable_encode() – 將 8 bit 字符串轉換成 quoted-printable 編碼的字符串。(PS:quoted-printable 編碼是 MIME 郵件中常用的編碼格式)
str_getcsv() – 將 CSV 字符串解析成數組。
stream_context_set_default() – 設置默認的 stream context(數據流環境?或者叫數據流資源?)。
stream_supports_lock() – 如果數據流支持鎖則返回 TRUE。
stream_context_get_params() – 從 stream context 中取回參數。
streamWrapper::stream_cast() – 取回基本的 stream resource(數據流資源)。
streamWrapper::stream_set_option() – 修改 stream(數據流)選項。
Date/Time:
date_add() – 將一個 DateTime 對象增加某個數量的天、月、年、小時、分鐘或者秒。
date_create_from_format() – 返回給定的格式的新 DateTime 對象。
date_diff() – 返回兩個 DateTime 對象的差。
date_get_last_errors() – 返回最近一次日期/時間操作產生的警告或者錯誤。
date_parse_from_format() – 獲得給定日期的信息。
date_sub() – 將一個 DateTime 對象減去某個數量的天、月、年、小時、分鐘或者秒。
timezone_version_get() – 返回時區數據庫(timezonedb)的版本。
GMP:
gmp_testbit() – Tests whether a bit is set.
Hash:
hash_copy() – Copy hashing context.
IMAP:
imap_gc() – Clears IMAP cache.
imap_utf8_to_mutf7() – Encode a UTF-8 string to modified UTF-7.
imap_mutf7_to_utf8() – Decode a modified UTF-7 string to UTF-8.
JSON:
json_last_error() – Returns the last JSON error that occurred.
MySQL Improved:
mysqli_fetch_all() – Fetches all result rows as an associative array, a numeric array, or both.
mysqli_get_connection_stats() – Returns statistics about the client connection.
mysqli_poll() – Poll connections.
mysqli_reap_async_query() – Get result from async query.
OpenSSL:
openssl_random_pseudo_bytes() – Returns a string of the given length specified, filled with pseudo-random bytes.
PCNTL:
pcntl_signal_dispatch() – Calls signal handlers for pending signals.
pcntl_sigprocmask() – Sets and retrieves blocked signals.
pcntl_sigtimedwait() – Wait for signals with a timeout.
pcntl_sigwaitinfo() – Wait for signals.
PCRE:
preg_filter() – Perform a regular expression search and replace, reutrning only results which matched the pattern.
Semaphore:
msg_queue_exists() – Check whether a message queue exists.
shm_has_var() – Checks whether a specific key exists inside a shared memory segment.
以下函數在所有操作系統中都能運行
acosh()
asinh()
atanh()
expm1()
log1p()
十、新的 stream wrappers
glob://
phar://
十一、新的類常量
PDO_FIREBIRD:
PDO::FB_ATTR_DATE_FORMAT - 日期格式
PDO::FB_ATTR_TIME_FORMAT - 時間格式
PDO::FB_ATTR_TIMESTAMP_FORMAT - timestamps格式.
十二、新的類方法
Date/Time:
DateTime::add() - 在一個DateTime類型上增加指定的日、月、年、小時、分、秒
DateTime::createFromFormat() - 根據指定的格式返回新DateTime
DateTime::diff() - 返回兩個DateTime的差
DateTime::getLastErrors() - 返回最近一次date/time操作的警告或錯誤信息
DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object.
Exception:
Exception::getPrevious() - 獲取上次錯誤信息
DOM:
DOMNode::getLineNo() - 獲取指定節點的行號
PDO_FIREBIRD:
PDO::setAttribute() - 設置屬性
Reflection:
ReflectionClass::getNamespaceName() - 返回類的命名空間名稱
ReflectionClass::getShortName() - 返回類的短名(即不包含namespace部分)
ReflectionClass::inNamespace() - 返回namespace中是否定義了該類
ReflectionFunction::getNamespaceName() - 返回已定義該函數的namespace的名稱
ReflectionFunction::getShortName() - 返回函數的短名(不包含namespace部分)
ReflectionFunction::inNamespace() - 返回函數是否已在namespace中定義
ReflectionProperty::setAccessible() - 設置非public屬性是否能被訪問
SPL:
SplObjectStorage::addAll() - Add all elements from another SplObjectStorage object.
SplObjectStorage::removeAll() - Remove all elements from another SplObjectStorage object.
XSL:
XSLTProcessor::setProfiling() - Sets the profiling output file.
十三、新擴展
PHP 5.3.0默認已添加以下擴展
Enchant - An abstraction layer above various spelling libraries
Fileinfo - An improved and more solid replacement, featuring full BC, for the Mimetype extension, which has been removed.
INTL - Internationalization extension. INTL is a wrapper around the » ICU library.
Phar - Implementation of PHP-Archive files.
SQLite3 - 支持SQLite3
mysqlnd is a new core library shipped with PHP. It is a PHP-specific replacement for libmysql.
mysqlnd will be used to build the mysql, mysqli and PDO_MySQL extensions if libmysql isnt found on the system.
It may also be used instead of libmysql even when libmysql is present. mysqlnd is recommended for all PHP installations for performance reasons.
十四、移除的擴展
以下擴展被移到PECL并不再作為PHP發行版的一部分
These extensions have been moved to PECL and are no longer part of the PHP distribution.
The PECL package versions of these extensions will be created according to user demand.
這些擴展的PECL包版本將以用戶的需要來創建
dbase - 不再保留
fbsql - 不再保留
fdf - 保留
ming - 保留
msql - 不再保留
ncurses - 保留
sybase - 不再繼續,請使用sybase_ct擴展來代替
mhash - 不再繼續,請使用hash擴展來代替,hash完全兼容mhash;使用舊方法將能繼續運行。
十五、擴展中的其他變化
在配置時以下擴展將無法被禁用
PCRE
Reflection
SPL
擴展行為的變化以及新功能
Date and Time - The TZ environment variable is no longer used to guess the timezone
cURL - cURL支持SSH
Network - dns_check_record()返回額外的鍵"entries", 包含域名的TXT記錄.
Hash - 支持SHA-224 和 salsa hash algorithms
mbstring - 支持 CP850編碼
OCI8 - A call to oci_close() on a persistent connection, or a variable referencing a persistent connection going out of scope,
will now roll back any uncommitted transaction. To avoid unexpected behavior, explicitly issue a commit or roll back as needed.
The old behavior can be enabled with the INI directive oci8.old_oci_close_semantics.
Database Resident Connection Pooling (DRCP) and Fast Application Notification (FAN) are now supported.
Oracle External Authentication is now supported (except on Windows).
The oci_bind_by_name() function now supports SQLT_AFC (aka the CHAR datatype).
OpenSSL - OpenSSL digest and cipher functions are now supported. It is also now possible to access the internal values of DSA, RSA and DH keys.
Session - Sessions will no longer store session-files in "/tmp" when open_basedir restrictions apply, unless "/tmp" is explicitly added to the list of allowed paths.
SOAP Now supports sending user supplied HTTP headers.
MySQLi 在主機名前添加"p:"將支持持久連接
Image Processing and GD The "JPG Support" index returned from gd_info() has been renamed to "JPEG Support".
十六、新的類
Date/Time:
DateInterval
DatePeriod
Phar:
Phar
PharData
PharException
PharFileInfo
SPL:
FilesystemIterator
GlobIterator
MultipleIterator
RecursiveTreeIterator
SplDoublyLinkedList
SplFixedArray
SplHeap
SplMaxHeap
SplMinHeap
SplPriorityQueue
SplQueue
SplStack
十七、新的全局常量
PHP Core:
__DIR__
__NAMESPACE__
E_DEPRECATED
E_USER_DEPRECATED
INI_SCANNER_NORMAL
INI_SCANNER_RAW
PHP_MAXPATHLEN
PHP_WINDOWS_NT_DOMAIN_CONTROLLER
PHP_WINDOWS_NT_SERVER
PHP_WINDOWS_NT_WORKSTATION
PHP_WINDOWS_VERSION_BUILD
PHP_WINDOWS_VERSION_MAJOR
PHP_WINDOWS_VERSION_MINOR
PHP_WINDOWS_VERSION_PLATFORM
PHP_WINDOWS_VERSION_PRODUCTTYPE
PHP_WINDOWS_VERSION_SP_MAJOR
PHP_WINDOWS_VERSION_SP_MINOR
PHP_WINDOWS_VERSION_SUITEMASK
cURL:
CURLOPT_PROGRESSFUNCTION
GD:
IMG_FILTER_PIXELATE
JSON:
JSON_ERROR_CTRL_CHAR
JSON_ERROR_DEPTH
JSON_ERROR_NONE
JSON_ERROR_STATE_MISMATCH
JSON_ERROR_SYNTAX
JSON_FORCE_OBJECT
JSON_HEX_TAG
JSON_HEX_AMP
JSON_HEX_APOS
JSON_HEX_QUOT
LDAP:
LDAP_OPT_NETWORK_TIMEOUT
libxml:
LIBXML_LOADED_VERSION
PCRE:
PREG_BAD_UTF8_OFFSET_ERROR
PCNTL:
BUS_ADRALN
BUS_ADRERR
BUS_OBJERR
CLD_CONTIUNED
CLD_DUMPED
CLD_EXITED
CLD_KILLED
CLD_STOPPED
CLD_TRAPPED
FPE_FLTDIV
FPE_FLTINV
FPE_FLTOVF
FPE_FLTRES
FPE_FLTSUB
FPE_FLTUND
FPE_INTDIV
FPE_INTOVF
ILL_BADSTK
ILL_COPROC
ILL_ILLADR
ILL_ILLOPC
ILL_ILLOPN
ILL_ILLTRP
ILL_PRVOPC
ILL_PRVREG
POLL_ERR
POLL_HUP
POLL_IN
POLL_MSG
POLL_OUT
POLL_PRI
SEGV_ACCERR
SEGV_MAPERR
SI_ASYNCIO
SI_KERNEL
SI_MESGQ
SI_NOINFO
SI_QUEUE
SI_SIGIO
SI_TIMER
SI_TKILL
SI_USER
SIG_BLOCK
SIG_SETMASK
SIG_UNBLOCK
TRAP_BRKPT
TRAP_TRACE
十八、INI文件處理的變化
PHP 5.3.0顯著改進了INI文件解析的性能,并且添加若干新語法功能
The standard php.ini files have been re-organized and renamed. php.ini-development contains settings recommded for use in development environments. php.ini-production contains settings recommended for use in production environments.
There is now support for two special sections: [PATH=/opt/httpd/www.example.com/] and [HOST=www.example.com]. Directives set in these sections cannot be overridden by user-defined INI files or at runtime. More information about these sections can be found here.
zend_extension_debug and zend_extension_ts have been removed. Use the zend_extension directive to load all Zend Extensions.
zend.ze1_compatibility_mode has been removed. If this INI directive is set to On, an E_ERROR error is emitted at startup.
It is now possible to use the full path to load modules using the "extension" directive.
"ini-variables" can now be used almost anywhere in a php.ini file.
Runtime tightening of open_basedir restrictions is now possible.
It is now possible to use alphanumeric or variable indices in INI option arrays.
get_cfg_var() is now able to return "array" INI options.
A new directive, mail.add_x_header, has been added.
user_ini.filename is new
user_ini.cache_ttl is also new
exit_on_timeout is new too
open_basedir is now PHP_INI_ALL
The following new ini directives have been added:
user_ini.filename and user_ini.cache_ttl for the new .htaccess-style user INI file mechanism.
Added mbstring.http_output_conv_mimetype. This directive specifies the regex pattern of content types for which mb_output_handler() is activated.
Added request_order. Allows controlling which external variables will be available in $_REQUEST.
The following ini directives have new default values:
session.use_only_cookies is now set to "1" (enabled) by default.
oci8.default_prefetch has changed from "10" to "100".
十九、其他變化
SplFileInfo::getpathinfo() 返回path name信息
SplObjectStorage now has ArrayAccess support. It is now also possible to store associative information with objects in SplObjectStorage.
In the GD extension, there is now pixelation support available through the imagefilter() function.
var_dump() 輸出將包含私有屬性
session_start() 失敗返回FALSE
property_exists() now checks the existence of a property independent of accessibility (like method_exists()).
Stream wrappers can now be used by include_path.
The initial parameter for array_reduce() can now be of any type.
The directory functions opendir(), scandir(), and dir() now use the default stream context if no explicit context is passed.
crypt() now has Blowfish and extended DES support, and crypt() features are now 100% portable. PHP has its own internal crypt implementation which drops into place when support for crypt or crypt_r is not found.
getopt() now accepts "long options" on all platforms. Optional values and = as a separator for short options are now supported.
fopen()有了新的模式選項(n), which passes O_NONBLOCK to the underlying open() system call. 這個模式已經能在windows上使用。
getimagesize() 支持icon文件(.ico).
mhash擴展移到PECL, 編譯時使用--with-mhash選項,hash擴展將兼容mhash。注意:hash擴展開啟兼容mhash,無需mhash庫的支持。
本文采用Creative Commons協議,復制本文需遵守三點:1、保留署名(鏈接);2、非商業性使用;3、再次創作的作品必須以相同的許可協議發布。
新聞熱點
疑難解答