Closures - http://php.net/closures
<?php
$getClosure = function($v) {
return function() use($v) {
echo "Hello World: $v!\n";
};
};
$closure = $getClosure(2);
$closure();
?>
Output
Namespaces - http://php.net/namespaces
<?php
// foo.php
namespace foo;
class bar {
function __construct() {
echo get_called_class();
}
}
?>
Using namespaced code
<?php
require './foo.php';
use foo\bar as b;
$a = new b;
?>
Output
Late Static Binding - http://php.net/lsb
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who(); // Normal class resolution
static::who(); // LSB
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
Output
get_called_class
<?php
abstract class Singleton {
private static $instances = array();
final public static function getInstance() {
$className = get_called_class();
if(!isset(self::$instances[$className])) {
self::$instances[$className] = new $className();
}
return self::$instances[$className];
}
}
class foo extends Singleton { }
class bar extends Singleton { }
$a = foo::getInstance();
$b = foo::getInstance();
$c = bar::getInstance();
echo '<pre>';
var_dump($a);
var_dump($b);
var_dump($c);
echo '</pre>';
?>
Output
object(foo)#204 (0) {
}
object(foo)#204 (0) {
}
object(bar)#177 (0) {
}
NOWDOC - http://php.net/nowdoc
<?php
echo <<< 'EOB'
NOWDOC is to HEREDOC as single quoted $trings are\n
to double quoted $trings in PHP.
EOB;
?>
Output
NOWDOC is to HEREDOC as single quoted $trings are\n
to double quoted $trings in PHP.
Ternary Shortcut
<?php
echo true ?: 'Hello';
echo false ?: 'World';
?>
Output
goto - http://php.net/goto
<?php
function foo() {
for($i=0, $j=1; $i<10; $i++) {
while($j++) {
if($j == 5) {
goto end;
}
}
}
end:
// run cleanup code
}
?>
DateInterval/DatePeriod
<?php
$db = new DateTime('2008-12-31');
$de = new DateTime('2009-12-31');
$di = DateInterval::createFromDateString('third tuesday of next month');
$dp = new DatePeriod($db, $di, $de, DatePeriod::EXCLUDE_START_DATE);
foreach($dp as $dt) {
echo $dt->format("F jS\n") . "<br>\n";
}
?>
Output
January 20th
February 17th
March 17th
April 21st
May 19th
June 16th
July 21st
August 18th
September 15th
October 20th
November 17th
December 15th