代码示例: echo preg_replace_callback('~-([a-z])~', function ($match) { return strtoupper($match[1]); }, 'hello-world'); // 输出 helloWorld $greet = function($name) { printf("Hello %srn", $name); };
$greet('World'); $greet('PHP'); //...在某个类中 $callback = function ($quantity, $product) use ($tax, &$total) { $pricePerItem = constant(__CLASS__ . "::PRICE_" . strtoupper($product)); $total += ($pricePerItem * $quantity) * ($tax + 1.0); }; array_walk($products, $callback); ?>
新增两个魔术方法__callStatic()和__invoke() PHP中原本有一个魔术方法__call(),当代码调用对象的某个不存在的方法时该魔术方法会被自动调用。新增的__callStatic()方法则只用于静态类方法。当尝试调用类中不存在的静态方法时,__callStatic()魔术方法将被自动调用。
代码示例: class MethodTest { public function __call($name, $arguments) { // 参数 $name 大小写敏感 echo "调用对象方法 '$name' " . implode(' -- ', $arguments). "n"; }
/** PHP 5.3.0 以上版本中本类方法有效 */ public static function __callStatic($name, $arguments) { // 参数 $name 大小写敏感 echo "调用静态方法 '$name' " . implode(' -- ', $arguments). "n"; } }
$obj = new MethodTest; $obj->runTest('通过对象调用');
MethodTest::runTest('静态调用'); // As of PHP 5.3.0 ?> 以上代码执行后输出如下: 调用对象方法'runTest' –- 通过对象调用 调用静态方法'runTest' –- 静态调用
以函数形式来调用对象时,__invoke()方法将被自动调用。
代码示例: class MethodTest { public function __call($name, $arguments) { // 参数 $name 大小写敏感 echo "Calling object method '$name' " . implode(', ', $arguments). "n"; }
/** PHP 5.3.0 以上版本中本类方法有效 */ public static function __callStatic($name, $arguments) { // 参数 $name 大小写敏感 echo "Calling static method '$name' " . implode(', ', $arguments). "n"; } }
$obj = new MethodTest; $obj->runTest('in object context');
MethodTest::runTest('in static context'); // As of PHP 5.3.0 ?>
新增Nowdoc语法,用法和Heredoc类似,但使用单引号。Heredoc则需要通过使用双引号来声明。 Nowdoc中不会做任何变量解析,非常适合于传递一段PHP代码。 代码示例: // Nowdoc 单引号PHP 5.3之后支持 $name = 'MyName';
echo <<<'EOT' My name is "$name". EOT; //上面代码输出 My name is "$name". ((其中变量不被解析) // Heredoc不加引号 echo << Hello World! FOOBAR; //或者双引号 PHP 5.3之后支持 echo <<<"FOOBAR" Hello World! FOOBAR; ?>
支持通过Heredoc来初始化静态变量、类成员和类常量。 代码示例: // 静态变量 function foo() { static $bar = << Nothing in here... LABEL; }
// 类成员、常量 class foo { const BAR = << Constant example FOOBAR;
public $baz = << Property example FOOBAR; } ?>
在类外也可使用const来定义常量 PHP中定义常量通常是用这种方式: 代码示例: define("CONSTANT", "Hello world."); ?>
PHP5.3新增了一种常量定义方式:
代码示例: const CONSTANT = 'Hello World'; ?>
三元运算符增加了一个快捷书写方式: ?: 原本格式为是(expr1) ? (expr2) : (expr3) 如果expr1结果为True,则返回expr2的结果。 PHP5.3新增一种书写方式,可以省略中间部分,书写为expr1 ?: expr3 如果expr1结果为True,则返回expr1的结果 HTTP状态码在200-399范围内均被认为访问成功 支持动态调用静态方法 代码示例:
class Test { public static function testgo() { echo "gogo!"; } }
$class = 'Test'; $action = 'testgo'; $class::$action(); //输出 "gogo!" ?>
支持嵌套处理异常(Exception) 新的垃圾收集器(GC),并默认启用
(责任编辑:admin) |