Created
August 30, 2022 11:40
-
-
Save judgej/9cb38d47a76273a823771b8ea7802cfc to your computer and use it in GitHub Desktop.
This file contains 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The laravel
tap
helper effectively does this:tap
does not have to modify the value it is given. For example, this is given1
and does nothing in the closure, so returns1
:The return value of the closure does nothing. So this still returns
1
and not2
as you may expect: