Skip to content

Instantly share code, notes, and snippets.

@daveh
Created January 11, 2022 09:10
Show Gist options
  • Save daveh/a62a6f78f63f7892e1d5e73e47dc9b94 to your computer and use it in GitHub Desktop.
Save daveh/a62a6f78f63f7892e1d5e73e47dc9b94 to your computer and use it in GitHub Desktop.
What's new in PHP 8.0 (code to accompany https://youtu.be/ve9bKHZG47c)
<?php
#[\Attribute(Attribute::TARGET_CLASS)]
class Route
{
public function __construct(
public string $path
)
{}
}
#[Setup, AllowedRoles("admin", "manager"), Route("home")]
class Controller
{
}
$reflector = new ReflectionClass(Controller::class);
$attributes = $reflector->getAttributes();
var_dump($attributes[2]->newInstance());
<?php
class User
{
/*
public int $id;
private string $name;
public function __construct(int $id, string $name)
{
$this->id = $id;
$this->name = $name;
}
*/
public function __construct(public int $id, private string $name)
{
}
}
<?php
$status_code = 404;
switch ($status_code) {
case 200:
case 300:
$message = null;
break;
case 404:
$message = 'Not found';
break;
case 500:
$message = 'Server error';
break;
default:
$message = 'Unknown status code';
break;
}
$message = match ($status_code) {
200, 300 => null,
404 => "Not found",
500 => "Server error",
default => "Unknown status code"
};
<?php
$path = "one/two/three";
$parts = explode(string: $path, separator: "/");
print_r($parts);
setcookie("lang", "en", httponly: true);
<?php
// if (strpos("One Two Three", "Two") !== false) {
if (str_contains("One Two Three", "Two")) {
// Found
} else {
// Not found
}
$starts = str_starts_with("One Two Three", "One"); // true
$ends = str_ends_with("One Two Three", "Three"); // true
<?php
try {
// Some code that could throw an exception
} catch (InvalidArgumentException) {
echo "Invalid argument";
} catch (OutOfRangeException) {
echo "Out of range";
} catch (Exception) {
echo "Something went wrong";
}
<?php
$country = null;
if ($session !== null) {
$user = $session->user;
if ($user !== null) {
$address = $user->getAddress();
if ($address !== null) {
$country = $address->country;
}
}
}
$country = $session?->user?->getAddress()?->country;
<?php
/*
if ($nullable_value === null) {
throw new InvalidArgumentException();
}
$value = $nullable_value;
*/
$value = $nullable_value ?? throw new InvalidArgumentException();
<?php
declare(strict_types=1);
class Discount
{
/**
* @var int|float $percentage
*/
private int|float $percentage;
public function setPercentage(int|float $value) {
$this->percentage = $value;
}
public function getPercentage(): int|float {
return $this->percentage;
}
}
$discount = new Discount;
$discount->setPercentage(20.5);
var_dump($discount->getPercentage());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment