Fork me on GitHub

PHP 7

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

Linux install CA cert file

Self signed certificates throw error and can make CLI scripts fail. Here is the procedure to use to import cert file at a system level.

Tested with debian 10.

cp my-cert-file.crt /usr/local/share/ca-certificates
update-ca-certificates

Clean your git repo with BFG Repo-Cleaner

Use case : delete the medias from my git repo that contains huge files.

Download bgf.jar from https://rtyley.github.io/bfg-repo-cleaner/

git clone --mirror https://git.mycompany.com/myrepo.git

java -jar ../bfg-1.13.0.jar --delete-folders medias myrepo.git

cd myrepo.git

git reflog expire --expire=now --all && git gc --prune=now --aggressive

git push

Size 400Mo -> 30 Mo