Skip to content

Support primary constructors#193

Open
thekid wants to merge 2 commits into
masterfrom
feature/primary-constructors
Open

Support primary constructors#193
thekid wants to merge 2 commits into
masterfrom
feature/primary-constructors

Conversation

@thekid

@thekid thekid commented Jul 5, 2026

Copy link
Copy Markdown
Member

Builds on xp-framework/ast#63 and adds primary constructor support to the compiler.

Examples

Temperature:

use lang\IllegalArgumentException;

class Temp(
  public private(set) float $celsius= 100 {
    set {
      if ($value < -273.15) {
        throw new IllegalArgumentException($value.' is below absolute zero');
      }
      $this->celsius= $value;
    }
  }
) { }
$ xp -w 'new Temp(celsius: -300)'
Uncaught exception: Exception lang.IllegalArgumentException (-300 is below absolute zero)
  at Temp::$celsius::set(-300) [line 6 of Temp.php]
  at Temp::__construct(-300) [line 1 of (command line argument)]
  at <main>::include((0x17)'(command line argument)') [line 163 of Code.class.php]
  at xp.runtime.Code::run(array[1]) [line 30 of Dump.class.php]
  at xp.runtime.Dump::main(array[1]) [line 399 of class-main.php]

Ranges:

class Range(public readonly int $start, public readonly int $end) implements IteratorAggregate {

  public function getIterator(): Traversable {
    if ($this->start > $this->end) {
      for ($i= $this->start; $i >= $this->end; $i--) yield $i;
    } else {
      for ($i= $this->start; $i <= $this->end; $i++) yield $i;
    }
  }
}
$ xp -w '[...new Range(10, 1)]'
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant