Skip to content

Instantly share code, notes, and snippets.

@IMSoP
Last active June 7, 2020 15:44
Show Gist options
  • Save IMSoP/2082f2abe76d562c3b0ee258be15f1d6 to your computer and use it in GitHub Desktop.
Save IMSoP/2082f2abe76d562c3b0ee258be15f1d6 to your computer and use it in GitHub Desktop.
<?php
sealed class Token {
abstract public function isSignificant(): bool;
class Identifier {
public function __construct(public string $name) {}
public function isSignificant(): bool { return true; }
}
class Whitespace() {
public function isSignificant(): bool { return false; }
}
class Comment() {
public function __construct(public string $comment) {}
public function isSignificant(): bool { return false; }
}
}
<?php
union Token {
case Identifier(public string $name);
case Whitespace;
case Comment(public string $comment);
public function isSignificant(): bool {
return match($this) {
self::Identifier => true,
self::Whitespace => false,
self::Comment => false
};
}
}
<?php
enum Token {
case Identifier(public string $name) = self(true);
case Whitespace = self(false);
case Comment(public string $comment) = self(false);
protected function __construct(private bool $isSignificant) {}
public function isSignificant(): bool {
return $this->isSignificant;
}
}
<?php
enum Token {
protected function __construct(private bool $isSignificant) {}
case Identifier(true) {
public function __construct(public string $name) {}
};
case Whitespace(false);
case Comment(false) {
public function __construct(public string $comment) {}
};
public function isSignificant(): bool {
return $this->isSignificant;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment