Fork me on GitHub

PHP 7 post

PHP 7: The Important Stuff

Basic PHP 7 cheat sheet from symfonycasts.

Throwable

Both \Exception and \Error implements \Throwable:

<?php
try {
    undefinedFunction();
} catch (\Throwable $error) {
    echo 'Now if you write bad code, you can catch it! ' . $error->getMessage();
}
echo "\n\nContinue processing file...";

Scalar Type Hints

string, int, float, bool, array, callable, iterable

public function setName(string $name)

Weak Mode (defaut mode) versus Strict Mode

declare(strict_types = 1);

Return Types

string, int, float, bool, array, callable, iterable

public function getName(): string

Nullable Types

public function getFunFact(): ?string

Void Types

public function setFunFact(?string $funFact): void

Private Constants

private const AVATAR_FILE_PREFIX = '/images';

The iterable Pseudo-Type

public function feed(iterable $food): string

The Multi Exception Catch

    try {
        if (random_int(0, 1)) {
            throw new NoCookieForYou();
        }
        throw new NoCookiesLeft();
    } catch (NoCookieForYou | NoCookiesLeft $e) {
        $whisper = sprintf('Crazy Dave whispered "%s"', $e->getMessage());
    }

spaceship operator <=>

It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression.

print( 1 <=> 1);print("<br/>");
print( 1 <=> 2);print("<br/>");
print( 2 <=> 1);print("<br/>");

source

Null Coalescing Operator ??

$username = $_GET['username'] ?? 'not passed';

Equivalent code using ternary operator:

$username = isset($_GET['username']) ? $_GET['username'] : 'not passed';

Source

Categories: dev