Miscellaneous

Runtime defined Constants

define("CURRENT\_DATE", date('Y-m-d'));
// One possible representation
echo CURRENT_DATE;   # => 2021-01-05
# => CURRENT\_DATE is: 2021-01-05
echo 'CURRENT\_DATE is: ' . CURRENT_DATE; 

fopen() mode

- -
r Read
r+ Read and write, prepend
w Write, truncate
w+ Read and write, truncate
a Write, append
a+ Read and write, append

Regular expressions

$str = "Visit Quickref.me";
echo preg\_match("/qu/i", $str); # => 1

See: Regex in PHP

Nullsafe Operator

// As of PHP 8.0.0, this line:
$result = $repo?->getUser(5)?->name;
// Equivalent to the following code:
if (is\_null($repo)) {
    $result = null;
} else {
    $user = $repository->getUser(5);
    if (is\_null($user)) {
        $result = null;
    } else {
        $result = $user->name;
    }
}

See also: Nullsafe Operator

Custom exception

class MyException extends Exception {
    // do something
}

Usage

try {
    $condition = true;
    if ($condition) {
        throw new MyException('bala');
    }
} catch (MyException $e) {
    // Handle my exception
}

Exception in PHP 8.0

$nullableValue = null;
try {
    $value = $nullableValue ?? throw new InvalidArgumentException();
} catch (InvalidArgumentException) { // Variable is optional
    // Handle my exception
    echo "print me!";
}

Basic error handling

try {
    // Do something
} catch (Exception $e) {
    // Handle exception
} finally {
    echo "Always print!";
}
Comments