Created
August 30, 2022 11:40
-
-
Save judgej/9cb38d47a76273a823771b8ea7802cfc 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 | |
| class ImmutableClass | |
| { | |
| protected $property1; | |
| protected $property2; | |
| // Clone, set value, return the clone. | |
| public function withProperty1($value) | |
| { | |
| $clone = clone $this; | |
| $clone->property1 = $value; | |
| return clone; | |
| } | |
| // Same actions in one line using laravel tap. | |
| public function withProperty2($value) | |
| { | |
| return tap(clone $this, fn($clone) => $clone->property2 = $value); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The laravel
taphelper effectively does this:tapdoes not have to modify the value it is given. For example, this is given1and does nothing in the closure, so returns1:The return value of the closure does nothing. So this still returns
1and not2as you may expect: