PHP code example of xp-lang / xp-records

1. Go to this page and download the library: Download xp-lang/xp-records 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-records example snippets


// Declaration
namespace com\example;

use IteratorAggregate, Traversable;

record Range(int $lo, int $hi) implements IteratorAggregate {
  public function getIterator(): Traversable {
    for ($i= $this->lo; $i <= $this->hi; $i++) {
      yield $i;
    }
  }
}

// Usage
$r= new Range(1, 10);
$r->lo();       // 1
$r->hi();       // 10
$r->toString(); // "com.example.Range(lo: 1, hi: 10)"

foreach ($r as $item) {
  // 1, 2, 3, ... 10
}

use lang\IllegalArgumentException;

record Range(int $lo, int $hi) {
  init {
    if ($this->lo > $this->hi) {
      throw new IllegalArgumentException('Lower border may not exceed upper border');
    }
  }
}

// Using the declaration from above:
$r= new Range(1, 10);

// Use https://wiki.php.net/rfc/short_list_syntax (>= PHP 7.1)
[$lo, $hi]= $r();

// Optionally map the members, returns the string "1..10"
$string= $r(fn($lo, $hi) => "{$lo}..{$hi}");