Skip to content

Instantly share code, notes, and snippets.

@judgej
Created August 30, 2022 11:40
Show Gist options
  • Save judgej/9cb38d47a76273a823771b8ea7802cfc to your computer and use it in GitHub Desktop.
Save judgej/9cb38d47a76273a823771b8ea7802cfc to your computer and use it in GitHub Desktop.
<?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);
}
}
@judgej
Copy link
Author

judgej commented Aug 30, 2022

The laravel tap helper effectively does this:

  1. Evaluates the first parameter.
  2. Does something with it using the closure of the second parameter.
  3. Returns the evaluated value, which mayt now be modified.

tap does not have to modify the value it is given. For example, this is given 1 and does nothing in the closure, so returns 1:

tap(1, fn() => null)

The return value of the closure does nothing. So this still returns 1 and not 2 as you may expect:

tap(1, fn($v) => ++$v)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment