Last active
March 13, 2022 06:43
-
-
Save azjezz/a95f641383801e9eb8f88003df0b297d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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