Skip to content

Commit

Permalink
add example about optional argument
Browse files Browse the repository at this point in the history
  • Loading branch information
yceruto committed Apr 19, 2024
1 parent 0866433 commit eb0c4b8
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,28 @@ $user = findUser(1)->expect('the user exists.'); // throws LogicException if it
$dto = findUser(1)->mapOr(UserDto::from(...), UserDto::new());
// do something safely with $dto instance...
```

## Example 2: Handling the presence or absence of a value in a function argument

You can also use the `Option` type to handle the presence or absence of a value in a function argument.

```php
use Std\Type\Option;

/**
* @param Option<User> $user
*/
function greet(Option $user): string
{
return $user->match(
some: fn (User $u) => "Hello, {$u->name()}!",
none: fn () => 'Hello, World!',
);
}

$user = new User(name: 'Alice');

echo greet(some($user)); // Outputs: Hello, Alice!
echo greet(none()); // Outputs: Hello, World!
```

0 comments on commit eb0c4b8

Please sign in to comment.