<!--START RESERVED FOR FUTURE USE INCLUDE FILES--><!-- include java script once we verify teams wants to use this and it will work on dbcs and cyrillic characters --><!--END RESERVED FOR FUTURE USE INCLUDE FILES-->
需求
除了对 PHP 和 HTML 有基本的认识以外,无需太多其他方面的知识便可阅读本文。每当文中提到 PHP V5.3 时,指的是 V5.3.0。
考察的特性
本文主要考察 PHP V5.3 的以下特性:
延迟静态绑定
名称空间
类方法重载
变量解析和 heredoc
但是,在继续之前,需要设置 PHP V5.3。
回页首
设置
PHP 广为人知的一个特点就是设置起来有点麻烦。这也许是因为 PHP 是安装在 Web 服务器(例如 Apache)上的,而且常常需要连接到外部数据库(例如 MySQL)。而且,某种意义上,PHP 脚本是嵌入在 HTML 代码中的。换句话说,PHP 这种技术横跨多个复杂的领域。所以,在编写 PHP 脚本代码之前,必须越过很多的障碍。我希望可以改善这一现状,但是与软件技术有关的很多事情仍然很困难。
不过,对于那些使用 Apple Macs 的幸运读者来说,设置过程再简单不过了:
<?php
class A {
public static function who() {
echo 'Calling who method from class '.__CLASS__;
}
public static function test() {
static::who();
}
}
class B extends A {
public static function who() {
echo 'Calling who method from class '.__CLASS__;
}
}
B::test();
?>
<?php
class OverloadedMethodTest {
public function __call($name, $arguments) {
// The value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(', ', $arguments)。 "\n";
}
/** As of PHP 5.3.0 */
public static function __callStatic($name, $arguments) {
// The value of $name is case sensitive.
echo "Calling static method '$name' "
. implode(', ', $arguments)。 "\n";
}
}
$obj = new OverloadedMethodTest;
$obj->runOverloadedTest('in an object context');
OverloadedMethodTest::runOverloadedTest('in a static context'); // As of PHP 5.3.0
?>
清单 4 中的代码产生以下输出:
Calling object method 'runOverloadedTest' in an object context
Calling static method 'runOverloadedTest' in a static context
在清单 4 中,注意重载的代码是如何根据调用代码来推断方法名和参数的:
$obj->runOverloadedTest('in an object context');
OverloadedMethodTest::runOverloadedTest('in a static context'); // As of PHP 5.3.0
<?php
$beverage = 'coffee';
// The following works; "'" is an invalid
character for variable names
echo "$beverage's taste is great";
// The following won't work; 's' is a valid
character for variable names but the
echo "He drank a number of $beverages";
variable is "$beverage"
echo "He drank some ${beverage}s"; // works
echo "He drank some {$beverage}s"; // works
?>
清单 5 中的代码产生以下输出:
coffee's taste is great
He drank a number of
He drank some coffees
He drank some coffees