|
| 1 | +--TEST-- |
| 2 | +Friends: RFC example 3 (UserBuilder and LoggedUserBuilder) |
| 3 | +--FILE-- |
| 4 | +<?php |
| 5 | + |
| 6 | +class User { |
| 7 | + friend UserBuilder; |
| 8 | + |
| 9 | + public protected(set) ?int $userId = null; |
| 10 | + public protected(set) ?string $username = null; |
| 11 | + |
| 12 | + // Protected constructor - use the UserBuilder |
| 13 | + protected function __construct() {} |
| 14 | +} |
| 15 | + |
| 16 | +class UserBuilder { |
| 17 | + |
| 18 | + public function newWithId(int $userId): User { |
| 19 | + $u = new User(); |
| 20 | + $u->userId = $userId; |
| 21 | + return $u; |
| 22 | + } |
| 23 | + |
| 24 | + public function newWithName(string $username): User { |
| 25 | + $u = new User(); |
| 26 | + $u->username = $username; |
| 27 | + return $u; |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +class LoggedUserBuilder extends UserBuilder { |
| 32 | + |
| 33 | + public function newWithId(int $userId): User { |
| 34 | + echo "Creating user with id: $userId\n"; |
| 35 | + return parent::newWithId($userId); |
| 36 | + } |
| 37 | + |
| 38 | + public function newWithName(string $username): User { |
| 39 | + echo "Creating user with name: $username\n"; |
| 40 | + return parent::newWithName($username); |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +$builder = new UserBuilder(); |
| 45 | + |
| 46 | +$alice = $builder->newWithId(1); |
| 47 | +var_dump($alice); |
| 48 | + |
| 49 | +$bob = $builder->newWithName("Bob"); |
| 50 | +var_dump($bob); |
| 51 | + |
| 52 | +echo "\n\n----------\n\n"; |
| 53 | + |
| 54 | +// LoggedUserBuilder doesn't actually access anything protected, that is all |
| 55 | +// done in the parent:: calls, this works fine |
| 56 | +$loggedBuilder = new LoggedUserBuilder(); |
| 57 | +$charlie = $loggedBuilder->newWithId(3); |
| 58 | +var_dump($charlie); |
| 59 | + |
| 60 | +$daniel = $loggedBuilder->newWithName("Daniel"); |
| 61 | +var_dump($daniel); |
| 62 | + |
| 63 | +?> |
| 64 | +--EXPECTF-- |
| 65 | +object(User)#%d (2) { |
| 66 | + ["userId"]=> |
| 67 | + int(1) |
| 68 | + ["username"]=> |
| 69 | + NULL |
| 70 | +} |
| 71 | +object(User)#%d (2) { |
| 72 | + ["userId"]=> |
| 73 | + NULL |
| 74 | + ["username"]=> |
| 75 | + string(3) "Bob" |
| 76 | +} |
| 77 | + |
| 78 | + |
| 79 | +---------- |
| 80 | + |
| 81 | +Creating user with id: 3 |
| 82 | +object(User)#%d (2) { |
| 83 | + ["userId"]=> |
| 84 | + int(3) |
| 85 | + ["username"]=> |
| 86 | + NULL |
| 87 | +} |
| 88 | +Creating user with name: Daniel |
| 89 | +object(User)#%d (2) { |
| 90 | + ["userId"]=> |
| 91 | + NULL |
| 92 | + ["username"]=> |
| 93 | + string(6) "Daniel" |
| 94 | +} |
0 commit comments