Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaveLiddament/40130a7a107478bf6f92fcbb0b01a2fc to your computer and use it in GitHub Desktop.
Save DaveLiddament/40130a7a107478bf6f92fcbb0b01a2fc to your computer and use it in GitHub Desktop.
PHP generics notation for static analysis

Notation for generics to PHP: #<>

Disclaimer: I assume someone has already suggested this and there are good reasons it hasn't happened!

Inspired by a conversation with @pronskiy after my talk "PHP Generics Today (Almost)" at IPC Munich

Examples:

class Queue #<T of object>
{
  private array#<int,T> $queue = [];

  public function add(#<T> $item): void {...}

  publc function next(): #<T> {...}
}

$personQueue = new Queue#<Person>();


interface Repository #<T> {...}
class PersonRepository implements Repository#<Person> {...}

Create a new AST node Generics which contains anything between the angle brackets in #<>. NOTE only a subset of PHP langugage will be allowed in #<>

Any children of the Generics AST node is ignored when generating op codes, but is used by static analysis.

Advantages

  • Docblocks not needed for generics
  • Obvious which type information is checked at runtime and which is ONLY checked by static analysis
  • Notation is, I assume, possible with current PHP tokeniser
  • Notation is not a breaking change. # is treated as a comment, or when combined with #[] an attribute.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment