xp-lang/xp-generics

XP generics for PHP

v2.0.0 2024-03-24 13:44 UTC

This package is auto-updated.

Last update: 2024-04-28 22:53:17 UTC


README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.4+ Supports PHP 8.0+ Latest Stable Version

Plugin for the XP Compiler which adds support for XP generics.

Example

// Declaration
namespace com\example;

class PriorityQueue<E> {
  private $elements;
  private $comparator= null;
  private $sorted= true;

  public function __construct(E... $elements) {
    $this->elements= $elements;
  }

  public function comparing(?function(E, E): int $comparator): self {
    $this->comparator= $comparator;
    return $this;
  }

  public function push(E $element): void {
    $this->elements[]= $element;
    $this->sorted= false;
  }

  public function pop(): ?E {
    if (!$this->sorted) {
      $this->comparator ? usort($this->elements, $this->comparator) : sort($this->elements);
      $this->sorted= true;
    }
    return array_pop($this->elements);
  }
}


// Usage
$q= new PriorityQueue<string>();
$q->push('Test');

$q->push(123); // lang.IllegalArgumentException

Installation

After installing the XP Compiler into your project, also include this plugin.

$ composer require xp-framework/compiler
# ...

$ composer require xp-lang/xp-generics
# ...

No further action is required.

See also