Skip to content

Instantly share code, notes, and snippets.

@bdelespierre
Last active July 5, 2017 14:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdelespierre/8a42095d4aa713d7149a8dcd06537ffc to your computer and use it in GitHub Desktop.
Save bdelespierre/8a42095d4aa713d7149a8dcd06537ffc to your computer and use it in GitHub Desktop.
A brief history of PHP features

PHP New Features CheatSheet

The neatest PHP cheatsheet around. Trust me, I'm a random Gist from GitHub :octocat:

PHP 7.1

Initial Release 2016-12-01 : Nullable types, Void functions, Symmetric array destructuring, Class constant visibility, iterable pseudo-type, Multi catch exception handling, Support for keys in list(), Support for negative string offsets, Convert callables to Closures with Closure::fromCallable(), Asynchronous signal handling

function foo(): ?string {}
function foo(?string $bar) {}
function foo(): void {}
[$a,$b] = [1,2];
foreach ([[1,2],[3,4]] as [$a,$b]);
class Foo
{
    const A = 1;
    public const B = 2;
    protected const C = 3;
    private const D = 4;
}
function foo(iterable $it) {}
try {} catch (RuntimeException | LogicException $e) {}
list('a' => $foo, 'b' => $bar) = ['a' => 1, 'b' => 2];
foreach ([['a' => 1, 'b' => 2], ['a' => 3, 'b' => 4]] as list('a' => $foo, 'b' => $bar));
echo "abc"[-1]; // c
$fn = Closure::fromCallable([Foo::class, 'barMethod']);
pcntl_async_signals(true); // turn on async signals

Summary » PHP 7.1

PHP 7.0

Initial Release 2015-12-03 : Scalar type declarations, Return type declarations, Null coalescing operator, Spaceship operator, Constant arrays using define(), Anonymous classes, Unicode codepoint escape syntax, Closure::call(), Filtered unserialize(), IntlChar, Expectations, Group use declarations, Generator Return Expressions, Generator delegation, Integer division with intdiv(), Session options, preg_replace_callback_array(), CSPRNG Functions, list() can always unpack objects implementing ArrayAccess, Other Features

function foo(string $s, int $i, float $f, bool $b) {}
function foo(): array
$a = $b[1] ?? 2;
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
define('ARR', [1,2,3]);
$o = new class {};
echo "\u{aa}";
$fn = function() { return $this->x; };
$fn->call(new class { $x = 1 }); // 1
$data = unserialize($foo, ["allowed_classes" => false]);
$data = unserialize($foo, ["allowed_classes" => [Foo::class, Bar::class]]);
printf('%x', IntlChar::CODEPOINT_MAX); // 10ffff
echo IntlChar::charName('@'); // COMMERCIAL AT
var_dump(IntlChar::ispunct('!')); // bool(true)
ini_set('assert.exception', 1);
class CustomError extends AssertionError {}
assert(false, new CustomError('Some error message'));
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
$gen = (function() { yield 1; yield 2; return 3; })();
foreach ($gen as $val);
$gen->getReturn(); // 3
function foo() { yield 1; yield 2; yield from bar(); }
function bar() { yield 3; yield 4; }
intdiv(10, 3); // 3
session_start([
    'cache_limiter' => 'private',
    'read_and_close' => true,
]);
preg_replace_callback_array([
    '~[a]+~' => function($match) {},
    '~[b]+~' => function($match) {},
], $subject);
random_bytes();
random_int();
list($a, $b) = new arrayObject([1,2]);
(clone $foo)->bar();

Summary » PHP 7.0

PHP 5.6

Initial Release 2014-08-28 : Constant expressions, Variadic functions via ..., Argument unpacking via ..., Exponentiation via **, use function and use const, phpdbg, Default character encoding, php://input is reusable, Large file uploads, GMP supports operator overloading, hash_equals() for timing attack safe string comparison, __debugInfo(), gost-crypto hash algorithm, pgsql async support

const ONE = 1;
const TWO = ONE * 2;
const ARR = [ONE, TWO];

class C {
    const THREE = TWO + 1;
    const ONE_THIRD = ONE / self::THREE;
    const SENTENCE = 'The value of THREE is '.self::THREE;
    public function f($a = ONE + self::THREE) {}
}
function foo(...$arg) { return array_sum($args); }
$args = [2,3];
foo(1, ...$args); // 6
2 ** 3; // 2x2x2 = pow(2,3) = 8
use const Name\Space\FOO;
use function Name\Space\foo;
// PHP now includes an interactive debugger called phpdbg implemented as a SAPI module
ini_get('default_charset'); // UTF-8
$payload = file_get_contents('php://input');
// Files larger than 2 gigabytes in size are now accepted
gmp_init(41) + 1; // 42
hash_equals(crypt("123", "#salt#", crypt(filter_input(INPUT_POST, 'pass'), "#salt#")));
class Foo
{
    private $prop = "bar";

    public function __debugInfo()
    {
        return ["prop" => "foo" . $this->prop];
    }
}

var_dump(new Foo); // foobar
hash("gost-crypto", "The quick brown fox jumps over the lazy dog.");
$conn = pg_connect("dbname=foo", PGSQL_CONNECT_ASYNC);

Summary » PHP 5.6

PHP 5.5

Initial Release 2013-06-20 : Generators added, finally keyword added, New password hashing API, foreach now supports list(), empty() supports arbitrary expressions, array and string literal dereferencing, Class name resolution via ::class, OPcache extension added, foreach now supports non-scalar keys

function xrange($start, $limit, $step = 1) {
    for ($i = $start; $i <= $limit; $i += $step) {
        yield $i;
    }
}
try {
    throw new Exception("foobar");
} catch (Exception $e) {
    /*re*/throw $e;
} finally {
    echo "I'm always executed, not matter what!";
}
password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
foreach ([[1,2],[3,4]] as list($a, $b));
function always_false() { return false; }
empty(always_false()); // true
[1,2,3][1]; // 2
"123"[2]; // 3
Foo\Bar::class;
// OPcache improves PHP performance by storing precompiled script bytecode in shared memory,
// thereby removing the need for PHP to load and parse scripts on each request.
foreach ($iterator as $object => $value);

Summary » PHP 5.5

PHP 5.4

Initial Release 2012-02-01 : Support for traits has been added, Short array syntax has been added, Function array dereferencing has been added, Closures now support $this, <?= is now always available, Class member access on instantiation has been added, Class::{expr}() syntax is now supported, Binary number format has been added, Improved parse error messages and improved incompatible arguments warnings, The session extension can now track the upload progress of files, Built-in development web server in CLI mode

trait Foo { public function hello() { echo "hello!"; } }
class Bar { use Foo; }
echo new Bar; // "hello!"
$arr = ['one' => 1, 'two' => 2, 'three' => 3];
function arr() { return [1,2,3]; }
echo arr()[0]; // 1
$fn = Closure::bind(function() { echo $this->foo; }, (object)['foo' => 'bar']);
$fn(); // 'bar'
<p><?="hello!"?></p>
echo (new Foo)->bar();
echo Foo::{"get".$bar}();
echo 0b101010; // 42
// ...
$key = ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")];
var_dump($_SESSION[$key]);
$ php -S localhost:8000

Summary » PHP 5.4

PHP 5.3

Initial Release 2010-07-22 : Support for namespaces has been added, Support for Late Static Bindings has been added, Support for jump labels (limited goto) has been added, Support for native Closures (Lambda/Anonymous functions) has been added, There are two new magic methods, __callStatic() and __invoke(), Nowdoc syntax is now supported, similar to Heredoc syntax, but with single quotes, It is now possible to use Heredocs to initialize static variables and class properties/constants, Heredocs may now be declared using double quotes, complementing the Nowdoc syntax, Constants can now be declared outside a class using the const keyword, The ternary operator now has a shorthand form: ?:, The HTTP stream wrapper now considers all status codes from 200 to 399 to be successful, Dynamic access to static methods is now possible, Exceptions can now be nested, A garbage collector for circular references has been added, and is enabled by default, The mail() function now supports logging of sent email via the mail.log configuration directive

namespace Foo\Bar;
use Another\Namespace\Class as Something;
class A
{
    const FOO = 1;

    public static function bar()
    {
        return static::FOO;
    }
}

class B extends A
{
    const FOO = 2;
}

echo B::bar(); // 2

XKCD Goto

goto a;
echo 'Foo'; // never printed
a:
echo 'Bar';
$fn = function() {};
class Foo
{
    public static function __callStatic($method, $args)
    {
        echo $method;
    }
}

Foo::something(); // 'something'

class Bar
{
    public function __invoke()
    {
        return 'foobar';
    }
}

$o = new Bar;
echo $o(); // 'foobar'
$name = 'Robert Paulson';
echo <<< EOF
His name is {$name}.
His name is {$name}.
His name is {$name}.
EOF;
class foo
{
    public $bar = <<< EOT
bar
EOT;
}
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;
const FOO = "bar";
echo $a ? 'yes!' : 'nope :(';
// ...
echo Foo::{$bar}();
throw new RuntimeException("something went wrong...", 0, $previousException);
gc_collect_cycles();
$logfile = ini_get('mail.log');

Summary » PHP 5.3

Glossary

Summary » Glossary

Credits

Licence Creative Commons

PHP New Features CheatSheet by Benjamin Delespierre is licensed under Creative Commons Attribution 4.0 International.

Based from The PHP Manual by The PHP Group.

Social icons from Foundation.

Summary » Credits

@JesusTheHun
Copy link

Thanks !
You have a typo in the exemple code of preg_replace_callback_array() ;)

@bdelespierre
Copy link
Author

@JesusTheHun Fixed! Thanks for the review 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment