Skip to content

Instantly share code, notes, and snippets.

@azjezz
Last active March 13, 2022 06:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azjezz/a95f641383801e9eb8f88003df0b297d to your computer and use it in GitHub Desktop.
Save azjezz/a95f641383801e9eb8f88003df0b297d to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App;
struct User {
string $identifier;
}
struct PasswordAuthenticated {
string $password;
}
struct SecurityUser extends User, PasswordAuthenticated {
array $roles = ['user'];
}
$first = SecurityUser { identifier: 'foo', password: 'bar' };
var_dump($first->roles); // ['user'], pre-defined
$user = SecurityUser { identifier: 'foo', password: 'bar', roles: ['user', 'admin'] };
var_dump($user->roles); // ['user', 'admin'], defined in initliaztion
$other = $user with { identifier: 'bar' };
/**
* @template T of User
* @param T $user
* @return T
*/
function foo(User $user): User {
echo $user->identifier;
return $user with { identifier: 'baz' };
}
$other = foo($other);
assert($other instanceof SecurityUser);
// follows definition order, identifier, then password, then roles.
foreach($other as $column => $value) {
echo "$column\n";
}
// output:
// identifier
// password
// roles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment