Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

PHP8 - What's New In PHP8?

Cheat Sheet
by Dave Child (DaveChild) via cheatography.com/1/cs/27364/

PHP8 Variable Types Union types Constr​uctor property promotion (cont)

Class/​int​‐ An instance of the class or public function foo(Foo|Bar ​ ​ ​ ​ ​ ​ ​ ​public int $amount,
erface name interface $input): int|float; ​ ​ ​ ) {}
self The same class the type is You can now specify more than one type in
}
used in a type hint: In the above example Currency and int
parent The parent of the class the • The void type cannot be part of a union. are both automa​tically made public
type is used in • Unions can be nullable by including null properties of the class and assigned values
callable Something callable as a type or preceding with a question on constr​uction.
mark.
bool A boolean
Weak maps
int An integer
Named arguments
class Foo
float A float
function foo(string $a, int $b, {
string A string
?string $c = null) ​ ​ ​ ​private WeakMap $cache;
array An array {
iterable Array or traver​sable ​ ​ ​ ... ​ ​ ​ ​public function getSom​eth​‐
object An object } ing​Wit​hCa​chi​ng(​object $obj):

mixed Any value foo( object


​ ​ ​ c: 'value c', ​ ​ ​ {
Return Types
​ ​ ​ a: 'value a' ​ ​ ​ ​ ​ ​ ​ ​return $this-​>ca​che​‐
void Function will not return
); [$obj]
anything
Pass values to functions and methods by ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ??= $this-​>co​mpu​teS​‐
static Function may return
name, regardless of the order in which they ome​thi​ngE​xpe​nsi​ve(​$obj);
static
are defined. ​ ​ ​ }
}
New mixed type
Attributes A weak map allows for storage of key-value
Mixed means any one of:
use pairs, but the PHP garbage collection will
array bool callable drop a weak map element where the only
App\Attributes\ExampleAttribute;
string int resource #[Exam​ple​Att​ribute] reference to it is the weak map itself.
float null object class Foo
{ Throw expression
Note that because mixed already contains
null, it is not nullable itself. ​ ​ ​ ​#[E​xam​ple​Att​ribute] $triggerError = fn () => throw
​ ​ ​ ​public const FOO = 'foo'; new MyError();
Return static $foo = $bar['​off​set'] ?? throw
​ ​ ​ ​#[E​xam​ple​Att​ribute] new Custom​Ex(​'of​fset');
class Foo
​ ​ ​ ​public $x;
{ Throw is now an expression instead of a
​ ​ ​ ​public function test(): statement, making it more flexible.
​ ​ ​ ​#[E​xam​ple​Att​ribute]
static
​ ​ ​ ​public function foo(#[​Exa​‐ Non-ca​pturing catches
​ ​ ​ {
mpl​eAt​tri​bute] $bar) { }
​ ​ ​ ​ ​ ​ ​ ​return new static(); try {
}
​ ​ ​ } ​ ​ ​ // Something goes wrong
} Structured metadata } catch (MySpe​cia​lEx​cep​tion) {
​ ​ ​ ​Log​::e​rro​r("S​ome​thing went
Static is now a valid return type.
Match expression wrong");

The nullsafe operator (copy) $result = match($input) { }


​ ​ ​ 0 => "​hel​lo", When you catch exceptions and throwa​‐
$foo = $bar->getBaz()?-
​ ​ ​ '1', '2', '3' => "​wor​ld", bles, you no longer need a variable.
>asFormatted();
};
Quickly check for nulls in method returns.
Switch statements made simple. Note, the ::class on objects
compar​isons made by match use strict
types. $foo = new Foo();
var_du​mp(​$fo​o::​class);
Constr​uctor property promotion
Works the same as get_c​las​s().
class Money
{
​ ​ ​ ​public function __cons​truct(
​ ​ ​ ​ ​ ​ ​ ​public Currency
$currency,

By Dave Child (DaveChild) Published 31st March, 2021. Sponsored by Readable.com


cheatography.com/davechild/ Last updated 31st March, 2021. Measure your website readability!
aloneonahill.com Page 1 of 3. https://readable.com
PHP8 - What's New In PHP8? Cheat Sheet
by Dave Child (DaveChild) via cheatography.com/1/cs/27364/

Trailing comma in parameter lists Breaking Changes

public function( Internal errors and engine warnings


​ ​ ​ ​string $param​eterA, have been made consistent and/or
​ ​ ​ int $param​eterB, reclas​sified.
​ ​ ​ Foo $objec​tfoo, The @ operator no longer silences
) { fatal errors.
​ ​ ​ // … The default error reporting level is
} now E_ALL.
You can now end a parameter list with a comma without an The default PDO error mode is no
error. longer silent.
Concat​enation precedence has
Create DateTime objects from interfaces changed - addition now precedes
DateTime::createFromInterface(DateTimeInterface concat​ena​tion.
$other); Namespaces can now include
DateTi​meI​mmu​tab​le:​:cr​eat​eFr​omI​nte​rfa​ce(​Dat​eTi​‐ reserved names.
meI​nte​rface $other); Refle​cti​onF​unc​tio​n::​isD​‐
isa​ble​d(), Refle​cti​onP​ara​‐
New Stringable interface met​er:​:ge​tCl​ass() and Refle​‐
class Foo cti​onP​ara​met​er:​:is​Cal​lab​‐
{ le() have been deprec​ated.
​ ​ ​ ​public function __toSt​ring(): string
There are more breaking and engine
​ ​ ​ { changes, this list is limited to those
​ ​ ​ ​ ​ ​ ​ ​return 'foo'; you are most likely to encounter. For
​ ​ ​ } a full run-down, check out Brent's
} article linked below.
function bar(st​rin​g|S​tri​ngable $strin​gable) {
/ … / } With Thanks
bar(new Foo()); This is a condensed version of the
bar('a​bc'); excellent PHP8 write-up you can
find by Brent at stitcher.io
New functions

str_c​ont​ain​s('​hay​stack', Does haystack contain


'needle') needle?

str_s​tar​ts_​wit​h('​hay​‐ Does haystack start with


stack', 'needle') needle?

str_e​nds​_wi​th(​'ha​yst​‐ Does haystack end with


ack', 'needle') needle?

fdiv() Handles division by zero


without an error.
get_d​ebu​g_t​ype() Like getty​pe() but with
more detail
get_r​eso​urc​e_id() Fetch the numeric ID of a
resource

By Dave Child (DaveChild) Published 31st March, 2021. Sponsored by Readable.com


cheatography.com/davechild/ Last updated 31st March, 2021. Measure your website readability!
aloneonahill.com Page 2 of 3. https://readable.com

You might also like