xp-framework / compiler

Compiles future PHP to today's PHP.
19 stars 0 forks source link

Implement typed properties for PHP < 7.4 #118

Closed thekid closed 2 years ago

thekid commented 3 years ago

See https://github.com/xp-framework/compiler/issues/108#issuecomment-886040965. The following example will now throw a TypeError for all PHP versions on the last line:

class T {
  public int $id;
}

$t= new T();
$t->id= 'Test';

Generates code for virtual properties to make reflection work seamlessly on it, see https://github.com/xp-framework/rfc/issues/340

⚠️ Restricted to instance properties due to https://bugs.php.net/bug.php?id=52225

thekid commented 3 years ago

Performance

<?php

use util\profiling\Timer;

class Property {
  public int $id;

  public static function main($args) {
    $t= new Timer()->start();

    $p= new self();
    for ($i= 0; $i < 10_000_000; $i++) {
      $p->id= $args[0];
    }

    printf("Elapsed: %.3f seconds\n", $t->elapsedTime());
    var_dump($p);
  }
}

PHP 8.0

$ xp compile -t PHP.8.0 Property.php  > Property.class.php
# ... 

$ xp Property.class.php 234
Elapsed: 0.521 seconds
object(Property)#30 (1) {
  ["id"]=>
  int(234)
}

PHP 7.0

$ xp compile -t PHP.7.0 Property.php  > Property.class.php
# ... 

$ xp Property.class.php 234
Elapsed: 2.649 seconds
object(Property)#30 (1) {
  ["__id":"Property":private]=>
  array(1) {
    ["id"]=>
    int(234)
  }
}

This shows the importance of a feature like @Danon suggested in #119

thekid commented 2 years ago

Superseded by #129