Skip to content

Instantly share code, notes, and snippets.

@Crell

Crell/sealed.php Secret

Created June 15, 2021 19:49
Show Gist options
  • Save Crell/4a43ddf10571ec15eb7c1d2c8727a060 to your computer and use it in GitHub Desktop.
Save Crell/4a43ddf10571ec15eb7c1d2c8727a060 to your computer and use it in GitHub Desktop.
<?php
sealed abstract class Maybe for Some, None {
const None = new None();
public static function Some(public readonly $val) {
return new Some($val);
}
}
class Some extends Maybe {
protected function __construct(public readonly $value) {}
public function bind(callable $c) {
return $c($this->value);
}
}
class None extends Maybe {
public function bind(callable $c) { return $this; }
}
function stuff(string $bla) {
return $blah == '' ? Maybe::None : strlen($blah);
}
// vs
sealed abstract class Maybe for Some, None {
protected static None $none;
public function None() {
return static::None ??= new None();
}
public static function Some(public readonly $val) {
return new Some($val);
}
}
function stuff(string $bla) {
return $blah == '' ? Maybe::None() : strlen($blah);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment