PHP code example of xp-lang / xp-generics

1. Go to this page and download the library: Download xp-lang/xp-generics library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

xp-lang / xp-generics example snippets


// 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